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: __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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
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 #20
Source File: test_runner.py    From schemathesis with MIT License 5 votes vote down vote up
def test_form_data(openapi_version, args):
    if openapi_version.is_openapi_3:
        pytest.xfail(reason="Multipart handling is broken for Open API 3.0. Ref: #640")
    app, kwargs = args

    def is_ok(response, case):
        assert response.status_code == 200

    def check_content(response, case):
        if isinstance(app, Flask):
            data = response.json
        else:
            data = response.json()
        assert isinstance(data["key"], str)
        assert data["value"].lstrip("-").isdigit()

    # When endpoint specifies parameters with `in=formData`
    # Then responses should have 200 status, and not 415 (unsupported media type)
    results = execute(**kwargs, checks=(is_ok, check_content), hypothesis_max_examples=3)
    # And there should be no errors or failures
    assert not results.has_errors
    assert not results.has_failures
    # And the application should receive 3 requests as specified in `max_examples`
    assert_incoming_requests_num(app, 3)
    # And the Content-Type of incoming requests should be `multipart/form-data`
    incoming_requests = get_incoming_requests(app)
    assert incoming_requests[0].headers["Content-Type"].startswith("multipart/form-data") 
Example #21
Source File: test_runner.py    From schemathesis with MIT License 5 votes vote down vote up
def test_headers_override(args):
    app, kwargs = args

    def check_headers(response, case):
        if isinstance(app, Flask):
            data = response.json
        else:
            data = response.json()
        assert data["X-Token"] == "test"

    init, *others, finished = prepare(
        **kwargs, checks=(check_headers,), headers={"X-Token": "test"}, hypothesis_max_examples=1
    )
    assert not finished.has_failures
    assert not finished.has_errors 
Example #22
Source File: test_runner.py    From schemathesis with MIT License 5 votes vote down vote up
def test_reproduce_code_with_overridden_headers(args, base_url):
    app, kwargs = args

    *_, after, finished = prepare(**kwargs, headers={"X-Token": "test"}, hypothesis_max_examples=1)
    assert finished.has_failures
    headers = {"X-Token": "test", "User-Agent": USER_AGENT}
    if isinstance(app, Flask):
        expected = f"requests.get('http://localhost/api/failure', headers={headers})"
    else:
        expected = f"requests.get('{base_url}/failure', headers={headers})"
    assert after.result.checks[1].example.requests_code == expected 
Example #23
Source File: abstract.py    From qb with MIT License 5 votes vote down vote up
def web_api(self, host='0.0.0.0', port=5000, debug=False):
        from flask import Flask, jsonify, request

        app = Flask(__name__)

        @app.route('/api/answer_question', methods=['POST'])
        def answer_question():
            text = request.form['text']
            guess, score = self.guess([text], 1)[0][0]
            return jsonify({'guess': guess, 'score': float(score)})

        app.run(host=host, port=port, debug=debug) 
Example #24
Source File: test_runner.py    From schemathesis with MIT License 5 votes vote down vote up
def get_schema_requests(app):
    if isinstance(app, Flask):
        return app.config["schema_requests"]
    return app["schema_requests"] 
Example #25
Source File: app.py    From recruit with Apache License 2.0 5 votes vote down vote up
def name(self):
        """The name of the application.  This is usually the import name
        with the difference that it's guessed from the run file if the
        import name is main.  This name is used as a display name when
        Flask needs the name of the application.  It can be set and overridden
        to change the value.

        .. versionadded:: 0.8
        """
        if self.import_name == '__main__':
            fn = getattr(sys.modules['__main__'], '__file__', None)
            if fn is None:
                return '__main__'
            return os.path.splitext(os.path.basename(fn))[0]
        return self.import_name 
Example #26
Source File: __init__.py    From maple-file with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_app(config):
    app = Flask(__name__)
    app.config.from_object(config)
    extension.init_app(app)
    auth.init_app(app)
    server.init_app(app)
    admin.init_app(app)
    router.init_app(app)
    return app 
Example #27
Source File: serve.py    From sagemaker-xgboost-container with Apache License 2.0 5 votes vote down vote up
def start():
        # NOTE: Stop Flask application when SIGTERM is received as a result of "docker stop" command.
        signal.signal(signal.SIGTERM, ScoringService.stop)

        ScoringService.app.config["MAX_CONTENT_LENGTH"] = ScoringService.MAX_CONTENT_LENGTH
        options = {
            "bind": "{}:{}".format("0.0.0.0", ScoringService.PORT),
            "workers": number_of_workers(),
            "worker_class": "gevent",
            "keepalive": 60,
            "post_worker_init": ScoringService.post_worker_init,
        }
        GunicornApplication(ScoringService.app, options).run() 
Example #28
Source File: app.py    From beavy with Mozilla Public License 2.0 5 votes vote down vote up
def get_locale():
    locale = None
    if current_user is not None and current_user.is_authenticated:
        locale = current_user.language_preference
    elif app.config.get("LANGUAGES") is not None:
        languages = app.config.get("LANGUAGES")
        locale = request.accept_languages.best_match(languages)
    return locale  # If no locale, Flask-ICU uses the default setting.


#  ------ Database setup is done after here ---------- 
Example #29
Source File: web.py    From dino with Apache License 2.0 5 votes vote down vote up
def create_app():
    _app = Flask(
            import_name=__name__,
            template_folder='admin/templates/',
            static_folder='admin/static/')

    # used for encrypting cookies for handling sessions
    _app.config['SECRET_KEY'] = 'abc492ee-9739-11e6-a174-07f6b92d4a4b'
    _app.config['ROOT_URL'] = environ.env.config.get(ConfigKeys.ROOT_URL, domain=ConfigKeys.WEB, default='/')

    message_queue_type = environ.env.config.get(ConfigKeys.TYPE, domain=ConfigKeys.QUEUE, default=None)
    if message_queue_type is None and not (len(environ.env.config) == 0 or environ.env.config.get(ConfigKeys.TESTING)):
        raise RuntimeError('no message queue type specified')

    message_queue = 'redis://%s' % environ.env.config.get(ConfigKeys.HOST, domain=ConfigKeys.CACHE_SERVICE, default='')
    message_channel = 'dino_%s' % environ.env.config.get(ConfigKeys.ENVIRONMENT, default='test')

    logger.info('message_queue: %s' % message_queue)

    _socketio = SocketIO(
            _app,
            logger=logger,
            engineio_logger=os.environ.get('DINO_DEBUG', '0') == '1',
            async_mode='eventlet',
            message_queue=message_queue,
            channel=message_channel)

    # preferably "emit" should be set during env creation, but the socketio object is not created until after env is
    environ.env.out_of_scope_emit = _socketio.emit

    _app.wsgi_app = ReverseProxied(ProxyFix(_app.wsgi_app))

    return _app, _socketio 
Example #30
Source File: test_spec.py    From spectree with Apache License 2.0 5 votes vote down vote up
def backend_app():
    return [
        ('flask', Flask(__name__)),
        ('falcon', falcon.API()),
        ('starlette', Starlette()),
    ]