Python flask.Flask() Examples

The following are 30 code examples of flask.Flask(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask , or try the search function .
Example #1
Source File: rl_data.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 14 votes vote down vote up
def make_web(queue):
    app = Flask(__name__)

    @app.route('/')
    def index():
        return render_template('index.html')

    def gen():
        while True:
            frame = queue.get()
            _, frame = cv2.imencode('.JPEG', frame)
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + frame.tostring() + b'\r\n')

    @app.route('/video_feed')
    def video_feed():
        return Response(gen(),
                        mimetype='multipart/x-mixed-replace; boundary=frame')

    try:
        app.run(host='0.0.0.0', port=8889)
    except:
        print('unable to open port') 
Example #2
Source File: app.py    From comport with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def create_app(config_object=ProdConfig):
    """An application factory, as explained here:
        http://flask.pocoo.org/docs/patterns/appfactories/

    :param config_object: The configuration object to use.
    """
    app = Flask(__name__)
    sslify = SSLify(app)

    # set config from the passed object
    app.config.from_object(config_object)
    # set additional config values from environ
    app.config['SLACK_WEBHOOK_URL'] = os.environ.get('SLACK_WEBHOOK_URL')

    register_extensions(app)
    register_blueprints(app)
    register_errorhandlers(app)
    register_template_globals(app)

    @app.before_first_request
    def before_first_request():
        register_logging(app)

    return app 
Example #3
Source File: __init__.py    From CTask with GNU General Public License v3.0 7 votes vote down vote up
def create_app(config_name):
    app = Flask(__name__)
    #app.config['JSON_AS_ASCII'] = False
    # 进行app配置 把自己的config设定导入到app中
    app.config.from_object(config[config_name])

    # 初始化app配置
    config[config_name].init_app(app)

    db.init_app(app)
    db.app = app

    # 初始化apscheduler
    scheduler.init_app(app)
    scheduler.start()

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .job import main as job_blueprint
    app.register_blueprint(job_blueprint,url_prefix='/v1/cron/job')

    return app 
Example #4
Source File: manage.py    From flask_simplelogin with MIT License 7 votes vote down vote up
def create_user(**data):
    """Creates user with encrypted password"""
    if 'username' not in data or 'password' not in data:
        raise ValueError('username and password are required.')

    # Hash the user password
    data['password'] = generate_password_hash(
        data.pop('password'),
        method='pbkdf2:sha256'
    )

    # Here you insert the `data` in your users database
    # for this simple example we are recording in a json file
    db_users = json.load(open('users.json'))
    # add the new created user to json
    db_users[data['username']] = data
    # commit changes to database
    json.dump(db_users, open('users.json', 'w'))
    return data


# [--- Flask Factories  ---] 
Example #5
Source File: __init__.py    From flask-session-tutorial with MIT License 6 votes vote down vote up
def create_app():
    """Construct the core flask_session_tutorial."""
    app = Flask(__name__, instance_relative_config=False)
    app.config.from_object('config.Config')

    # Initialize Plugins
    db.init_app(app)
    login_manager.init_app(app)
    sess.init_app(app)

    with app.app_context():
        from . import routes
        from . import auth
        from .assets import compile_static_assets, compile_auth_assets
        app.register_blueprint(routes.main_bp)
        app.register_blueprint(auth.auth_bp)

        # Create static asset bundles
        compile_static_assets(app)
        compile_auth_assets(app)

        # Create Database Models
        db.create_all()

        return app 
Example #6
Source File: unicorn_binance_websocket_api_manager.py    From unicorn-binance-websocket-api with MIT License 6 votes vote down vote up
def _start_monitoring_api_thread(self, host, port, warn_on_update):
        """
        Threaded method that servces the monitoring api

        :param host: IP or hostname to use
        :type host: str
        :param port: Port to use
        :type port: int
        :param warn_on_update: Should the monitoring system report available updates?
        :type warn_on_update: bool
        """
        logging.info("Starting monitoring API service ...")
        app = Flask(__name__)
        @app.route('/')
        @app.route('/status/')
        def redirect_to_wiki():
            logging.debug("Visit https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/wiki/UNICORN-"
                          "Monitoring-API-Service for further information!")
            return redirect("https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/wiki/"
                            "UNICORN-Monitoring-API-Service", code=302)

        api = Api(app)
        api.add_resource(BinanceWebSocketApiRestServer,
                         "/status/<string:statusformat>/",
                         "/status/<string:statusformat>/<string:checkcommandversion>",
                         resource_class_kwargs={'handler_binance_websocket_api_manager': self,
                                                'warn_on_update': warn_on_update})
        try:
            dispatcher = wsgi.PathInfoDispatcher({'/': app})
            self.monitoring_api_server = wsgi.WSGIServer((host, port), dispatcher)
            self.monitoring_api_server.start()
        except RuntimeError as error_msg:
            logging.critical("Monitoring API service is going down! - Info: " + str(error_msg))
        except OSError as error_msg:
            logging.critical("Monitoring API service is going down! - Info: " + str(error_msg)) 
Example #7
Source File: Server.py    From uplink with MIT License 6 votes vote down vote up
def _users_for_repo(user, repo_name, oldest_age=55):
    """ Returns users that have commited in a repo in the last N weeks """

    since = (datetime.now() - timedelta(weeks=oldest_age)).isoformat()
    r = await github.commits_for_repo(user, repo_name, since=since)
    r_json = await r.json()
    users = set()
    for commit in r_json:
        if "author" in commit and commit["author"] is not None:
            user = (
                commit["author"]["login"],
                commit["commit"]["author"]["email"],
                commit["commit"]["author"]["name"],
            )
            users.add(user)
    return list(users)


# Flask routes 
Example #8
Source File: server.py    From flask-api-template with MIT License 6 votes vote down vote up
def __init__(self):
        self.app = Flask(__name__)
        custom_errors = {
            'JsonInvalidError': {
                'status': 500,
                'message': 'JSON format not valid'
            },
            'JsonRequiredError': {
                'status': 400,
                'message': 'JSON input required'
            }
        }
        self.api = swagger.docs(Api(self.app, errors=custom_errors), apiVersion=API_VERSION_NUMBER)
        
        self.api.add_resource(DummyEndpoint, '/dummy', endpoint='dummy')
        self.api.add_resource(HelloEndpoint, '/hello', endpoint='hello') 
Example #9
Source File: test_spec.py    From spectree with Apache License 2.0 6 votes vote down vote up
def create_app():
    app = Flask(__name__)

    @app.route('/foo')
    @api.validate()
    def foo():
        pass

    @app.route('/bar')
    @api_strict.validate()
    def bar():
        pass

    @app.route('/lone', methods=['GET'])
    def lone_get():
        pass

    @app.route('/lone', methods=['POST'])
    def lone_post():
        pass

    return app 
Example #10
Source File: rest_connector.py    From thingsboard-gateway with Apache License 2.0 6 votes vote down vote up
def __init__(self, gateway, config, connector_type):
        super().__init__()
        self.__log = log
        self._default_converters = {
            "uplink": "JsonRESTUplinkConverter",
            "downlink": "JsonRESTDownlinkConverter"
        }
        self.__config = config
        self._connector_type = connector_type
        self.statistics = {'MessagesReceived': 0,
                           'MessagesSent': 0}
        self.__gateway = gateway
        self.__USER_DATA = {}
        self.setName(config.get("name", 'REST Connector ' + ''.join(choice(ascii_lowercase) for _ in range(5))))

        self._connected = False
        self.__stopped = False
        self.daemon = True
        self._app = Flask(self.get_name())
        self._api = Api(self._app)
        self.__rpc_requests = []
        self.__attribute_updates = []
        self.__fill_requests_from_TB()
        self.endpoints = self.load_endpoints()
        self.load_handlers() 
Example #11
Source File: app.py    From recruit with Apache License 2.0 6 votes vote down vote up
def make_config(self, instance_relative=False):
        """Used to create the config attribute by the Flask constructor.
        The `instance_relative` parameter is passed in from the constructor
        of Flask (there named `instance_relative_config`) and indicates if
        the config should be relative to the instance path or the root path
        of the application.

        .. versionadded:: 0.8
        """
        root_path = self.root_path
        if instance_relative:
            root_path = self.instance_path
        defaults = dict(self.default_config)
        defaults['ENV'] = get_env()
        defaults['DEBUG'] = get_debug_flag()
        return self.config_class(root_path, defaults) 
Example #12
Source File: app.py    From recruit with Apache License 2.0 6 votes vote down vote up
def update_template_context(self, context):
        """Update the template context with some commonly used variables.
        This injects request, session, config and g into the template
        context as well as everything template context processors want
        to inject.  Note that the as of Flask 0.6, the original values
        in the context will not be overridden if a context processor
        decides to return a value with the same key.

        :param context: the context as a dictionary that is updated in place
                        to add extra variables.
        """
        funcs = self.template_context_processors[None]
        reqctx = _request_ctx_stack.top
        if reqctx is not None:
            bp = reqctx.request.blueprint
            if bp is not None and bp in self.template_context_processors:
                funcs = chain(funcs, self.template_context_processors[bp])
        orig_ctx = context.copy()
        for func in funcs:
            context.update(func())
        # make sure the original values win.  This makes it possible to
        # easier add new variables in context processors without breaking
        # existing views.
        context.update(orig_ctx) 
Example #13
Source File: app.py    From recruit with Apache License 2.0 6 votes vote down vote up
def make_shell_context(self):
        """Returns the shell context for an interactive shell for this
        application.  This runs all the registered shell context
        processors.

        .. versionadded:: 0.11
        """
        rv = {'app': self, 'g': g}
        for processor in self.shell_context_processors:
            rv.update(processor())
        return rv

    #: What environment the app is running in. Flask and extensions may
    #: enable behaviors based on the environment, such as enabling debug
    #: mode. This maps to the :data:`ENV` config key. This is set by the
    #: :envvar:`FLASK_ENV` environment variable and may not behave as
    #: expected if set in code.
    #:
    #: **Do not enable development when deploying in production.**
    #:
    #: Default: ``'production'`` 
Example #14
Source File: app.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_cli_runner(self, **kwargs):
        """Create a CLI runner for testing CLI commands.
        See :ref:`testing-cli`.

        Returns an instance of :attr:`test_cli_runner_class`, by default
        :class:`~flask.testing.FlaskCliRunner`. The Flask app object is
        passed as the first argument.

        .. versionadded:: 1.0
        """
        cls = self.test_cli_runner_class

        if cls is None:
            from flask.testing import FlaskCliRunner as cls

        return cls(self, **kwargs) 
Example #15
Source File: app.py    From recruit with Apache License 2.0 6 votes vote down vote up
def process_response(self, response):
        """Can be overridden in order to modify the response object
        before it's sent to the WSGI server.  By default this will
        call all the :meth:`after_request` decorated functions.

        .. versionchanged:: 0.5
           As of Flask 0.5 the functions registered for after request
           execution are called in reverse order of registration.

        :param response: a :attr:`response_class` object.
        :return: a new response object or the same, has to be an
                 instance of :attr:`response_class`.
        """
        ctx = _request_ctx_stack.top
        bp = ctx.request.blueprint
        funcs = ctx._after_request_functions
        if bp is not None and bp in self.after_request_funcs:
            funcs = chain(funcs, reversed(self.after_request_funcs[bp]))
        if None in self.after_request_funcs:
            funcs = chain(funcs, reversed(self.after_request_funcs[None]))
        for handler in funcs:
            response = handler(response)
        if not self.session_interface.is_null_session(ctx.session):
            self.session_interface.save_session(self, ctx.session, response)
        return response 
Example #16
Source File: test_runner.py    From schemathesis with MIT License 6 votes vote down vote up
def assert_request(
    app: web.Application, idx: int, method: str, path: str, headers: Optional[Dict[str, str]] = None
) -> None:
    request = get_incoming_requests(app)[idx]
    assert request.method == method
    if request.method == "GET":
        # Ref: #200
        # GET requests should not contain bodies
        if not isinstance(app, Flask):
            if not isinstance(request.content, EmptyStreamReader):
                assert request.content._read_nowait(-1) != b"{}"
        else:
            assert request.data == b""
    assert request.path == path
    if headers:
        for key, value in headers.items():
            assert request.headers.get(key) == value 
Example #17
Source File: test_runner.py    From schemathesis with MIT License 6 votes vote down vote up
def test_payload_explicit_example(args):
    # When endpoint has an example specified
    app, kwargs = args
    kwargs.setdefault("hypothesis_phases", [Phase.explicit])
    result = execute(**kwargs)
    # Then run should be successful
    assert not result.has_errors
    assert not result.has_failures
    incoming_requests = get_incoming_requests(app)

    if isinstance(app, Flask):
        body = incoming_requests[0].json
    else:
        body = await incoming_requests[0].json()
    # And this example should be sent to the app
    assert body == {"name": "John"} 
Example #18
Source File: webapp.py    From ara-archive with GNU General Public License v3.0 6 votes vote down vote up
def create_app(config=None, app_name=None):
    if app_name is None:
        app_name = DEFAULT_APP_NAME

    if current_app:
        return current_app

    app = Flask(app_name)

    configure_app(app, config)
    configure_dirs(app)
    configure_logging(app)
    configure_errorhandlers(app)
    configure_template_filters(app)
    configure_context_processors(app)
    configure_blueprints(app)
    configure_static_route(app)
    configure_db(app)

    return app 
Example #19
Source File: __init__.py    From Flask-Large-Application-Example with MIT License 6 votes vote down vote up
def route(flask_app: Flask):
    from app.views.sample.api import SampleAPI

    handle_exception_func = flask_app.handle_exception
    handle_user_exception_func = flask_app.handle_user_exception
    # register_blueprint 시 defer되었던 함수들이 호출되며, flask-restful.Api._init_app()이 호출되는데
    # 해당 메소드가 app 객체의 에러 핸들러를 오버라이딩해서, 별도로 적용한 handler의 HTTPException 관련 로직이 동작하지 않음
    # 따라서 두 함수를 임시 저장해 두고, register_blueprint 이후 함수를 재할당하도록 함

    # - blueprint, api object initialize
    api_blueprint = Blueprint("api", __name__)
    api = Api(api_blueprint)

    # - route
    api.add_resource(SampleAPI, "/sample")

    # - register blueprint
    flask_app.register_blueprint(api_blueprint)

    flask_app.handle_exception = handle_exception_func
    flask_app.handle_user_exception = handle_user_exception_func 
Example #20
Source File: app_factory.py    From hydrus with MIT License 5 votes vote down vote up
def app_factory(api_name: str = "api") -> Flask:
    """Create an app object."""

    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret key'
    CORS(app)
    app.url_map.strict_slashes = False
    api = Api(app)

    api.add_resource(Index, "/{}/".format(api_name), endpoint="api")
    api.add_resource(Vocab, "/{}/vocab".format(api_name), endpoint="vocab")
    api.add_resource(
        Contexts,
        "/{}/contexts/<string:category>.jsonld".format(api_name),
        endpoint="contexts")
    api.add_resource(
        Entrypoint,
        "/{}/contexts/EntryPoint.jsonld".format(api_name),
        endpoint="main_entrypoint")
    api.add_resource(
        ItemCollection,
        "/{}/<string:path>".format(api_name),
        endpoint="item_collection")
    api.add_resource(
        Item,
        "/{}/<string:path>/<uuid:id_>".format(api_name),
        endpoint="item")
    api.add_resource(
        Items,
        "/{}/<string:path>/add/<int_list>".format(api_name),
        "/{}/<string:path>/add".format(api_name),
        "/{}/<string:path>/delete/<int_list>".format(api_name))

    return app 
Example #21
Source File: __init__.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def fetch_remote_manifests():
        """
        在 gevent 模式下,创建 Flask 对象时无法进行 HTTP 请求。因为此时 urllib2 是 gevent 补丁后的版本,而 gevent 引擎还没启动。
        因此我们只能在 fork 后的每个进程中进行请求。
        """
        cron_update_remote_manifest() 
Example #22
Source File: test_flask_pyoidc.py    From Flask-pyoidc with Apache License 2.0 5 votes vote down vote up
def create_flask_app(self):
        self.app = Flask(__name__)
        self.app.config.update({'SERVER_NAME': self.CLIENT_DOMAIN, 'SECRET_KEY': 'test_key'}) 
Example #23
Source File: zmirror.py    From zmirror with MIT License 5 votes vote down vote up
def dump_zmirror_snapshot(folder="error_dump", msg=None, our_response=None):
    """
    dump当前状态到文件
    :param folder: 文件夹名
    :type folder: str
    :param our_response: Flask返回对象, 可选
    :type our_response: Response
    :param msg: 额外的信息
    :type msg: str
    :return: dump下来的文件绝对路径
    :rtype: Union[str, None]
    """
    import pickle
    try:
        if not os.path.exists(zmirror_root(folder)):
            os.mkdir(zmirror_root(folder))
        _time_str = datetime.now().strftime('snapshot_%Y-%m-%d_%H-%M-%S')

        import config

        snapshot = {
            "time": datetime.now(),
            "parse": parse.dump(),
            "msg": msg,
            "traceback": traceback.format_exc(),
            "config": attributes(config, to_dict=True),
            "FlaskRequest": attributes(request, to_dict=True),
        }
        if our_response is not None:
            our_response.freeze()
        snapshot["OurResponse"] = our_response

        dump_file_path = os.path.abspath(os.path.join(zmirror_root(folder), _time_str + '.dump'))

        with open(dump_file_path, 'wb') as fp:
            pickle.dump(snapshot, fp, pickle.HIGHEST_PROTOCOL)
        return dump_file_path
    except:
        return None 
Example #24
Source File: zmirror.py    From zmirror with MIT License 5 votes vote down vote up
def zmirror_after_request(response):
    # 移除 connection_pool 中的锁
    if enable_connection_keep_alive:
        connection_pool.release_lock()
    return response


# ################# End Flask After Request ################

# ################# Begin Flask ################# 
Example #25
Source File: zmirror.py    From zmirror with MIT License 5 votes vote down vote up
def about_zmirror():
    return Response("""zmirror
version: {version}
Author: {author}
Github: {github_url}
Note: Love Luciaz Forever!

Mirroring: {source_site}
This site: {my_domain}
""".format(version=CONSTS.__VERSION__, author=CONSTS.__AUTHOR__,
           github_url=CONSTS.__GITHUB_URL__, source_site=target_domain,
           my_domain=my_host_name),
                    content_type='text/plain')


# ################# End Flask #################

# ################# Begin Post (auto)Exec Section #################

# ########### domain replacer prefix string buff ############### 
Example #26
Source File: test_gquery.py    From grlc with MIT License 5 votes vote down vote up
def setUpClass(self):
        self.loader = LocalLoader('./tests/repo/')
        self.app = Flask('unittests') 
Example #27
Source File: flask.py    From python-clean-architecture with MIT License 5 votes vote down vote up
def controller(self, route_name, template):
        """
        Function decorator factory that introduces Controller pattern into integration with Flask.
        """
        def decorator(wrapped):
            # TODO #52. implementation
            return self.route(wrapped)

        return decorator 
Example #28
Source File: server.py    From fine-lm with MIT License 5 votes vote down vote up
def __init__(self, app, options=None):
    """Creates the GUnicorn application.

    Args:
      app: A Flask application that will process requests.
      options: A dict of GUnicorn options.
    """
    self.options = options or {}
    self.application = app
    super(DebugFrontendApplication, self).__init__() 
Example #29
Source File: server.py    From fine-lm with MIT License 5 votes vote down vote up
def load(self):
    """Loads the application.

    Returns:
      The Flask application.
    """
    return self.application 
Example #30
Source File: bot_app.py    From botbuilder-python with MIT License 5 votes vote down vote up
def __init__(self):
        # Create the loop and Flask app
        self.loop = asyncio.get_event_loop()
        self.flask = Flask(__name__, instance_relative_config=True)
        self.flask.config.from_object(DefaultConfig)

        # Create adapter.
        # See https://aka.ms/about-bot-adapter to learn more about how bots work.
        self.settings = BotFrameworkAdapterSettings(
            self.flask.config["APP_ID"], self.flask.config["APP_PASSWORD"]
        )
        self.adapter = BotFrameworkAdapter(self.settings)

        # Catch-all for errors.
        async def on_error(adapter, context: TurnContext, error: Exception):
            # This check writes out errors to console log .vs. app insights.
            # NOTE: In production environment, you should consider logging this to Azure
            #       application insights.
            print(f"\n [on_turn_error]: {error}", file=sys.stderr)

            # Send a message to the user
            error_message_text = "Sorry, it looks like something went wrong."
            error_message = MessageFactory.text(
                error_message_text, error_message_text, InputHints.expecting_input
            )
            await context.send_activity(error_message)

            # pylint: disable=protected-access
            if adapter._conversation_state:
                # If state was defined, clear it.
                await adapter._conversation_state.delete(context)

        self.adapter.on_turn_error = MethodType(on_error, self.adapter)

        # Create the main dialog
        self.bot = MyBot()