Creates a Flask Application that can be started.
191826
def create(self):
        

        self._app = Flask(__name__,
                          static_url_path="",  # Mount static files at root '/'
                          static_folder=self.static_dir  # Serve static files from this directory
                          )

        for api_gateway_route in self.routing_list:
            path = PathConverter.convert_path_to_flask(api_gateway_route.path)
            for route_key in self._generate_route_keys(api_gateway_route.methods,
                                                       path):
                self._dict_of_routes[route_key] = api_gateway_route

            self._app.add_url_rule(path,
                                   endpoint=path,
                                   view_func=self._request_handler,
                                   methods=api_gateway_route.methods,
                                   provide_automatic_options=False)

        self._construct_error_handling()
675491
def init_app(self, app):
        # type: (Flask) -> None
        """"""
        self.client_id = app.config.get("MQTT_CLIENT_ID", "")

        if isinstance(self.client_id, unicode):
            self.client._client_id = self.client_id.encode('utf-8')
        else:
            self.client._client_id = self.client_id

        self.client._transport = app.config.get("MQTT_TRANSPORT", "tcp").lower()
        self.client._protocol = app.config.get("MQTT_PROTOCOL_VERSION", MQTTv311)

        self.client.on_connect = self._handle_connect
        self.client.on_disconnect = self._handle_disconnect
        self.username = app.config.get("MQTT_USERNAME")
        self.password = app.config.get("MQTT_PASSWORD")
        self.broker_url = app.config.get("MQTT_BROKER_URL", "localhost")
        self.broker_port = app.config.get("MQTT_BROKER_PORT", 1883)
        self.tls_enabled = app.config.get("MQTT_TLS_ENABLED", False)
        self.keepalive = app.config.get("MQTT_KEEPALIVE", 60)
        self.last_will_topic = app.config.get("MQTT_LAST_WILL_TOPIC")
        self.last_will_message = app.config.get("MQTT_LAST_WILL_MESSAGE")
        self.last_will_qos = app.config.get("MQTT_LAST_WILL_QOS", 0)
        self.last_will_retain = app.config.get("MQTT_LAST_WILL_RETAIN", False)

        if self.tls_enabled:
            self.tls_ca_certs = app.config["MQTT_TLS_CA_CERTS"]
            self.tls_certfile = app.config.get("MQTT_TLS_CERTFILE")
            self.tls_keyfile = app.config.get("MQTT_TLS_KEYFILE")
            self.tls_cert_reqs = app.config.get("MQTT_TLS_CERT_REQS",
                                                ssl.CERT_REQUIRED)
            self.tls_version = app.config.get("MQTT_TLS_VERSION",
                                              ssl.PROTOCOL_TLSv1)
            self.tls_ciphers = app.config.get("MQTT_TLS_CIPHERS")
            self.tls_insecure = app.config.get("MQTT_TLS_INSECURE", False)

        # set last will message
        if self.last_will_topic is not None:
            self.client.will_set(
                self.last_will_topic,
                self.last_will_message,
                self.last_will_qos,
                self.last_will_retain,
            )

        self._connect()
1191282
def init_app(self, app):
        
        app.config.setdefault('FLASK_AUTH_ALL', False)
        app.config.setdefault('FLASK_AUTH_REALM', 'Login Required')
        # Default set to bad file to trigger IOError
        app.config.setdefault('FLASK_HTPASSWD_PATH', '/^^^/^^^')

        # Load up user database
        try:
            self.load_users(app)
        except IOError:
            log.critical(
                'No htpasswd file loaded, please set `FLASK_HTPASSWD`'
                'or `FLASK_HTPASSWD_PATH` environment variable to a '
                'valid apache htpasswd file.'
            )

        # Allow requiring auth for entire app, with pre request method
        @app.before_request
        def require_auth():  # pylint: disable=unused-variable
            """Pre request processing for enabling full app authentication."""
            if not current_app.config['FLASK_AUTH_ALL']:
                return
            is_valid, user = self.authenticate()
            if not is_valid:
                return self.auth_failed()
            g.user = user
90530
def start():
    '''
    
    '''
    from wsgiref.simple_server import make_server

    # When started outside of salt-api __opts__ will not be injected
    if '__opts__' not in globals():
        globals()['__opts__'] = get_opts()

        if __virtual__() is False:
            raise SystemExit(1)

    mod_opts = __opts__.get(__virtualname__, {})

    # pylint: disable=C0103
    httpd = make_server('localhost', mod_opts['port'], application)

    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        raise SystemExit(0)
1300586
def before_init_app(self, app: FlaskUnchained):
        
        from .templates import (UnchainedJinjaEnvironment,
                                UnchainedJinjaLoader)
        app.jinja_environment = UnchainedJinjaEnvironment
        app.jinja_options = {**app.jinja_options,
                             'loader': UnchainedJinjaLoader(app)}
        app.jinja_env.globals['url_for'] = url_for

        for name in ['string', 'str']:
            app.url_map.converters[name] = StringConverter
232003
def make_action(app_factory, hostname='localhost', port=5000,
                threaded=False, processes=1, stream=None,
                sort_by=('time', 'calls'), restrictions=()):
    
    def action(hostname=('h', hostname), port=('p', port),
               threaded=threaded, processes=processes):
        """Start a new development server."""
        from werkzeug.serving import run_simple
        app = ProfilerMiddleware(app_factory(), stream, sort_by, restrictions)
        run_simple(hostname, port, app, False, None, threaded, processes)
    return action
376012
def create_app():
    

    # Setup Flask app and app.config
    app = Flask(__name__)
    app.config.from_object(__name__ + '.ConfigClass')

    # Initialize Flask extensions
    db = Flywheel(app)  # Initialize Flask-Flywheel
    mail = Mail(app)  # Initialize Flask-Mail

    # Define the User data model. Make sure to add flask_user UserMixin !!!
    class User(Model, UserMixin):
        __metadata__ = {
            "_name": "users",
            'throughput': {
                'read': 1,
                'write': 1,
            },
            'global_indexes': [
                GlobalIndex.all('email-username', 'username').throughput(read=1, write=1),
                GlobalIndex.all('email-index', 'email').throughput(read=1, write=1)
            ],
        }

        id = Field(hash_key=True)
        active = Field(data_type=bool)

        # User authentication information
        username = Field()
        password = Field()

        # User email information
        email = Field()
        email_confirmed_at = Field(data_type=datetime)

        # User information
        first_name = Field()
        last_name = Field()

        def get_id(self):
            if self.id is None:
                self.id = str(uuid.uuid1())
            return self.id

    # Setup Flask-User
    user_manager = UserManager(app, db, User)

    # Create all database tables
    db.engine.register(User)
    print('create_schema()')
    db.engine.create_schema()
    print('created_schema()')

    # The Home page is accessible to anyone
    @app.route('/')
    def home_page():
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
                <h2>Home page</h2>
                <p>This page can be accessed by anyone.</p><br/>
                <p><a href={{ url_for('home_page') }}>Home page</a> (anyone)</p>
                <p><a href={{ url_for('members_page') }}>Members page</a> (login required)</p>
            {% endblock %}
            """)

    # The Members page is only accessible to authenticated users
    @app.route('/members')
    @login_required  # Use of @login_required decorator
    def members_page():
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
                <h2>Members page</h2>
                <p>This page can only be accessed by authenticated users.</p><br/>
                <p><a href={{ url_for('home_page') }}>Home page</a> (anyone)</p>
                <p><a href={{ url_for('members_page') }}>Members page</a> (login required)</p>
            {% endblock %}
            """)

    return app
597120
def create_app():
    
    app = App.create_app(__name__)
    app.configure('.configs.settings')

    # yes, I should use blueprints; but I don't really care for such a small
    # toy app
    @app.route('/config')
    def get_config():
        """Get the current configuration of the app."""
        return jsonify(app.config)

    @app.route('/put_config', methods=['PUT'])
    def put_config():
        """Add to the current configuration of the app.

        Takes any JSON body and adds all keys to the configs with the provided
        values.
        """
        data = request.json()

        for key, val in data.items():
            app.config[key] = val

        return jsonify({'message': 'Config updated!'})

    return app
698604
def create_app(self):
        
        self.appinfo['accounts'] = self.get_accounts()
        self.log.debug('Pipeline Config\n%s', pformat(self.pipeline_config))
        self.log.debug('App info:\n%s', pformat(self.appinfo))
        jsondata = self.retrieve_template()
        wait_for_task(jsondata)

        self.log.info("Successfully created %s application", self.appname)
        return jsondata
1068257
def run(self):
        """"""
        self.logger.info("Running main flask method on port " +
                         str(self.settings['FLASK_PORT']))
        self.app.run(host='0.0.0.0', port=self.settings['FLASK_PORT'])
249470
def init_app(self, app, entry_point_group='invenio_celery.tasks',
                 **kwargs):
        """"""
        self.init_config(app)
        self.celery = FlaskCeleryExt(app).celery
        self.entry_point_group = entry_point_group
        app.extensions['invenio-celery'] = self
1320594
def make_app(include_packages: Sequence[str] = ()) -> Flask:
    
    # Load modules
    for package_name in include_packages:
        import_submodules(package_name)

    app = Flask(__name__)  # pylint: disable=invalid-name

    @app.errorhandler(ServerError)
    def handle_invalid_usage(error: ServerError) -> Response:  # pylint: disable=unused-variable
        response = jsonify(error.to_dict())
        response.status_code = error.status_code
        return response

    @app.route('/')
    def index() -> Response:  # pylint: disable=unused-variable
        return send_file('config_explorer.html')

    @app.route('/api/config/')
    def api_config() -> Response:  # pylint: disable=unused-variable
        """
        There are basically two things that can happen here.
        If this method is called with a ``Registrable`` class (e.g. ``Model``),
        it should return the list of possible ``Model`` subclasses.
        If it is called with an instantiable subclass (e.g. ``CrfTagger``),
        is should return the config for that subclass.

        This is complicated by the fact that some Registrable base classes
        (e.g. Vocabulary, Trainer) are _themselves_ instantiable.

        We handle this in two ways: first, we insist that the first case
        include an extra ``get_choices`` parameter. That is, if you call
        this method for ``Trainer`` with get_choices=true, you get the list
        of Trainer subclasses. If you call it without that extra flag, you
        get the config for the class itself.

        There are basically two UX situations in which this API is called.
        The first is when you have a dropdown list of choices (e.g. Model types)
        and you select one. Such an API request is made *without* the get_choices flag,
        which means that the config is returned *even if the class in question
        is a Registrable class that has subclass choices*.

        The second is when you click a "Configure" button, which configures
        a class that may (e.g. ``Model``) or may not (e.g. ``FeedForward``)
        have registrable subclasses. In this case the API request is made
        with the "get_choices" flag, but will return the corresponding config
        object if no choices are available (e.g. in the ``FeedForward``) case.

        This is not elegant, but it works.
        """
        class_name = request.args.get('class', '')
        get_choices = request.args.get('get_choices', None)

        # Get the configuration for this class name
        config = configure(class_name)
        try:
            # May not have choices
            choice5 = choices(class_name)
        except ValueError:
            choice5 = []

        if get_choices and choice5:
            return jsonify({
                    "className": class_name,
                    "choices": choice5
            })
        else:
            return jsonify({
                    "className": class_name,
                    "config": config.to_json()
            })

    return app
1266599
def init_app(self, app):
        
        self.enabled = app.config.get("CAPTCHA_ENABLE", True)
        self.digits = app.config.get("CAPTCHA_LENGTH", 4)
        self.max = 10**self.digits
        self.image_generator = ImageCaptcha()
        self.rand = SystemRandom()

        def _generate():
            if not self.enabled:
                return ""
            base64_captcha = self.generate()
            return Markup("<img src='{}'>".format("data:image/png;base64, {}".format(base64_captcha)))

        app.jinja_env.globals['captcha'] = _generate
        
        # Check for sessions that do not persist on the server. Issue a warning because they are most likely open to replay attacks.
        # This addon is built upon flask-session.
        session_type = app.config.get('SESSION_TYPE', None)
        if session_type is None or session_type == "null":
            raise RuntimeWarning("Flask-Sessionstore is not set to use a server persistent storage type. This likely means that captchas are vulnerable to replay attacks.")
        elif session_type == "sqlalchemy":
            # I have to do this as of version 0.3.1 of flask-session if using sqlalchemy as the session type in order to create the initial database.
            # Flask-sessionstore seems to have the same problem. 
            app.session_interface.db.create_all()
841769
def init_app(self, app):
        
        host = app.config.get('STATS_HOSTNAME', 'localhost')
        port = app.config.get('STATS_PORT', 8125)
        base_key = app.config.get('STATS_BASE_KEY', app.name)

        client = _StatsClient(
            host=host,
            port=port,
            prefix=base_key,
        )

        app.before_request(client.flask_time_start)
        app.after_request(client.flask_time_end)

        if not hasattr(app, 'extensions'):
            app.extensions = {}
        app.extensions.setdefault('stats', {})
        app.extensions['stats'][self] = client

        return client
1264812
def _create_app(self, color_depth, term='xterm'):
        
        output = Vt100_Output(_SocketStdout(self._send_packet),
                              lambda: self.size,
                              term=term,
                              write_binary=False)

        self.client_state = self.pymux.add_client(
            input=self._pipeinput, output=output, connection=self, color_depth=color_depth)

        print('Start running app...')
        future = self.client_state.app.run_async()
        print('Start running app got future...', future)

        @future.add_done_callback
        def done(_):
            print('APP DONE.........')
            print(future.result())
            self._close_connection()
123473
def create_reference_server_flask_app(cfg):
    """"""
    # Create Flask app
    app = Flask(__name__)
    Flask.secret_key = "SECRET_HERE"
    app.debug = cfg.debug
    # Install request handlers
    client_prefixes = dict()
    for api_version in cfg.api_versions:
        handler_config = Config(cfg)
        handler_config.api_version = api_version
        handler_config.klass_name = 'pil'
        handler_config.auth_type = 'none'
        # Set same prefix on local server as expected on iiif.io
        handler_config.prefix = "api/image/%s/example/reference" % (api_version)
        handler_config.client_prefix = handler_config.prefix
        add_handler(app, handler_config)
    return app
541588
def init_app(module, BASE_DIR, **kwargs):
    
    global app

    def init_config():
        """
        Load settings module and attach values to the application
        config dictionary
        """
        if 'FLASK_PHILO_SETTINGS_MODULE' not in os.environ:
            raise ConfigurationError('No settings has been defined')

        app.config['BASE_DIR'] = BASE_DIR

        # default settings
        for v in dir(default_settings):
            if not v.startswith('_'):
                app.config[v] = getattr(default_settings, v)

        app.debug = app.config['DEBUG']

        # app settings
        settings = importlib.import_module(
            os.environ['FLASK_PHILO_SETTINGS_MODULE'])
        for v in dir(settings):
            if not v.startswith('_'):
                app.config[v] = getattr(settings, v)

        def init_urls():
            # Reads urls definition from URLs file and bind routes and views
            urls_module = importlib.import_module(app.config['URLS'])
            for route in urls_module.URLS:
                app.add_url_rule(
                    route[0], view_func=route[1].as_view(route[2]))

        def init_logging():
            """
            initialize logger for the app
            """

            hndlr = logging.StreamHandler()
            formatter = logging.Formatter(
                '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
            hndlr.setFormatter(formatter)
            app.logger.addHandler(hndlr)
            log_level = app.config['LOG_LEVEL']
            app.logger.setLevel(getattr(logging, log_level))

        def init_flask_oauthlib():
            """
            http://flask-oauthlib.readthedocs.io/en/latest/oauth2.html
            """
            oauth.init_app(app)

        def init_cors(app):
            """
            Initializes cors protection if config
            """

            if 'CORS' in app.config:
                CORS(
                    app,
                    resources=app.config['CORS'],
                    supports_credentials=app.config.get(
                        "CORS_SUPPORT_CREDENTIALS",
                        False
                    ),
                    allow_headers=app.config.get(
                        "CORS_ALLOW_HEADERS",
                        "Content-Type,Authorization,accept-language,accept"
                    )
                )

        init_db(g, app)
        init_logging()
        init_urls()
        init_flask_oauthlib()
        init_jinja2(g, app)
        init_cors(app)
    app = Flask(module)
    init_config()
    return app