Python flask.Blueprint() Examples

The following are 30 code examples of flask.Blueprint(). 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: __init__.py    From papers with MIT License 7 votes vote down vote up
def create_app(env):
    app = Flask(__name__)
    app.config.from_object(config[env])

    # Start api/v1 Blueprint
    api_bp = Blueprint('api', __name__)
    api = Api(api_bp)

    api.add_resource(auth.AuthLogin, '/auth/login')
    api.add_resource(auth.AuthRegister, '/auth/register')
    api.add_resource(files.CreateList, '/users/<user_id>/files')
    api.add_resource(files.ViewEditDelete, '/users/<user_id>/files/<file_id>')

    app.register_blueprint(api_bp, url_prefix="/api/v1")
    # End api/v1 Blueprint

    return app 
Example #2
Source File: apispec.py    From flask-unchained with MIT License 6 votes vote down vote up
def register_routes(self, app: FlaskUnchained):
        bp = Blueprint('api-docs', __name__,
                       url_prefix=app.config.API_REDOC_URL_PREFIX.rstrip('/'),
                       template_folder=os.path.join(
                           os.path.dirname(os.path.abspath(__file__)), 'templates'))

        # Serve json spec at `API_REDOC_URL_PREFIX/openapi.json` by default
        bp.add_url_rule(app.config.API_OPENAPI_JSON_PATH,
                        endpoint='openapi_json',
                        view_func=self._openapi_json)

        # Serve ReDoc at `API_REDOC_URL_PREFIX/` by default
        bp.add_url_rule(app.config.API_REDOC_PATH,
                        endpoint='openapi_redoc',
                        view_func=self._openapi_redoc)

        app.register_blueprint(bp, register_with_babel=False) 
Example #3
Source File: csrf.py    From jbox with MIT License 6 votes vote down vote up
def exempt(self, view):
        """A decorator that can exclude a view from csrf protection.

        Remember to put the decorator above the `route`::

            csrf = CsrfProtect(app)

            @csrf.exempt
            @app.route('/some-view', methods=['POST'])
            def some_view():
                return
        """
        if isinstance(view, Blueprint):
            self._exempt_blueprints.add(view.name)
            return view
        if isinstance(view, string_types):
            view_location = view
        else:
            view_location = '%s.%s' % (view.__module__, view.__name__)
        self._exempt_views.add(view_location)
        return view 
Example #4
Source File: blueprints.py    From Flask-Large-Application-Example with MIT License 6 votes vote down vote up
def _factory(partial_module_string, url_prefix):
    """Generates blueprint objects for view modules.

    Positional arguments:
    partial_module_string -- string representing a view module without the absolute path (e.g. 'home.index' for
        pypi_portal.views.home.index).
    url_prefix -- URL prefix passed to the blueprint.

    Returns:
    Blueprint instance for a view module.
    """
    name = partial_module_string
    import_name = 'pypi_portal.views.{}'.format(partial_module_string)
    template_folder = 'templates'
    blueprint = Blueprint(name, import_name, template_folder=template_folder, url_prefix=url_prefix)
    return blueprint 
Example #5
Source File: extension.py    From flask-apispec with MIT License 6 votes vote down vote up
def add_swagger_routes(self):
        blueprint = flask.Blueprint(
            'flask-apispec',
            __name__,
            static_folder='./static',
            template_folder='./templates',
            static_url_path='/flask-apispec/static',
        )

        json_url = self.app.config.get('APISPEC_SWAGGER_URL', '/swagger/')
        if json_url:
            blueprint.add_url_rule(json_url, 'swagger-json', self.swagger_json)

        ui_url = self.app.config.get('APISPEC_SWAGGER_UI_URL', '/swagger-ui/')
        if ui_url:
            blueprint.add_url_rule(ui_url, 'swagger-ui', self.swagger_ui)

        self.app.register_blueprint(blueprint) 
Example #6
Source File: custom.py    From rasa_wechat with Apache License 2.0 6 votes vote down vote up
def blueprint(self, on_new_message):
        custom_webhook = Blueprint('custom_webhook', __name__)

        @custom_webhook.route("/", methods=['GET'])
        def health():
            return jsonify({"status": "ok"})

        @custom_webhook.route("/webhook", methods=['POST'])
        def receive():
            payload = request.json
            sender = payload.get("sender", None)
            text = payload.get("message", None)
            on_new_message(UserMessage(text, self.out_channel, sender))
            return "success"

        return custom_webhook 
Example #7
Source File: blueprints.py    From gitlab-tools with GNU General Public License v3.0 6 votes vote down vote up
def _factory(partial_module_string: str, url_prefix: str=None) -> Blueprint:
    """Generates blueprint objects for view modules.

    Positional arguments:
    partial_module_string -- string representing a view module without the absolute path (e.g. 'home.index' for
        gitlab-tools.views.home.index).
    url_prefix -- URL prefix passed to the blueprint.

    Returns:
    Blueprint instance for a view module.
    """
    name = partial_module_string
    import_name = 'gitlab_tools.views.{}'.format(partial_module_string)
    template_folder = 'templates'
    blueprint = Blueprint(name, import_name, template_folder=template_folder, url_prefix=url_prefix)
    return blueprint 
Example #8
Source File: api.py    From zou with GNU Affero General Public License v3.0 6 votes vote down vote up
def load_plugin(app, plugin):
    """
    Load a given plugin as an API plugin: add configured routes to the API. It
    assumes that the plugin is already loaded in memory has a blueprint
    structure.
    """
    routes = [
        ("/plugins%s" % route_path, resource)
        for (route_path, resource) in plugin.routes
        if len(route_path) > 0 and route_path[0] == "/"
    ]
    plugin.routes = routes
    plugin.blueprint = Blueprint(plugin.name, plugin.name)
    plugin.api = api_utils.configure_api_from_blueprint(
        plugin.blueprint, plugin.routes
    )
    app.register_blueprint(plugin.blueprint)
    app.logger.info("Plugin %s loaded." % plugin.name)
    return plugin 
Example #9
Source File: __init__.py    From flask-smorest with MIT License 6 votes vote down vote up
def _register_doc_blueprint(self):
        """Register a blueprint in the application to expose the spec

        Doc Blueprint contains routes to
        - json spec file
        - spec UI (ReDoc, Swagger UI).
        """
        api_url = self._app.config.get('OPENAPI_URL_PREFIX', None)
        if api_url is not None:
            blueprint = flask.Blueprint(
                'api-docs',
                __name__,
                url_prefix=_add_leading_slash(api_url),
                template_folder='./templates',
            )
            # Serve json spec at 'url_prefix/openapi.json' by default
            json_path = self._app.config.get(
                'OPENAPI_JSON_PATH', 'openapi.json')
            blueprint.add_url_rule(
                _add_leading_slash(json_path),
                endpoint='openapi_json',
                view_func=self._openapi_json)
            self._register_redoc_rule(blueprint)
            self._register_swagger_ui_rule(blueprint)
            self._app.register_blueprint(blueprint) 
Example #10
Source File: server.py    From python-slack-events-api with MIT License 6 votes vote down vote up
def __init__(self, signing_secret, endpoint, emitter, server):
        self.signing_secret = signing_secret
        self.emitter = emitter
        self.endpoint = endpoint
        self.package_info = self.get_package_info()

        # If a server is passed in, bind the event handler routes to it,
        # otherwise create a new Flask instance.
        if server:
            if isinstance(server, (Flask, Blueprint, LocalProxy)):
                self.bind_route(server)
            else:
                raise TypeError("Server must be an instance of Flask, Blueprint, or LocalProxy")
        else:
            Flask.__init__(self, __name__)
            self.bind_route(self) 
Example #11
Source File: factory.py    From flask-restful-example with MIT License 6 votes vote down vote up
def register_api(app, routers):
    for router_api in routers:
        if isinstance(router_api, Blueprint):
            app.register_blueprint(router_api)
        else:
            try:
                endpoint = router_api.__name__
                view_func = router_api.as_view(endpoint)
                # url默认为类名小写
                url = '/{}/'.format(router_api.__name__.lower())
                if 'GET' in router_api.__methods__:
                    app.add_url_rule(url, defaults={'key': None}, view_func=view_func, methods=['GET', ])
                    app.add_url_rule('{}<string:key>'.format(url), view_func=view_func, methods=['GET', ])
                if 'POST' in router_api.__methods__:
                    app.add_url_rule(url, view_func=view_func, methods=['POST', ])
                if 'PUT' in router_api.__methods__:
                    app.add_url_rule('{}<string:key>'.format(url), view_func=view_func, methods=['PUT', ])
                if 'DELETE' in router_api.__methods__:
                    app.add_url_rule('{}<string:key>'.format(url), view_func=view_func, methods=['DELETE', ])
            except Exception as e:
                raise ValueError(e) 
Example #12
Source File: test_frontend_filters.py    From udata with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_i18n_alternate_links_outside_i18n_blueprint(self, app, client):
        test = Blueprint('test', __name__)

        @test.route('/not-i18n/<key>/')
        def i18n(key):
            return render_template_string('{{ i18n_alternate_links() }}')

        app.register_blueprint(test)
        app.config['DEFAULT_LANGUAGE'] = 'en'
        app.config['LANGUAGES'] = {
            'en': 'English',
            'fr': 'Français',
            'de': 'German',
        }

        response = client.get(url_for('test.i18n', key='value', param='other'))
        assert response.data == b'' 
Example #13
Source File: test_blueprint.py    From prometheus_flask_exporter with MIT License 6 votes vote down vote up
def test_blueprint(self):
        blueprint = Blueprint('test-blueprint', __name__)

        @blueprint.route('/test')
        @self.metrics.summary('requests_by_status', 'Request latencies by status',
                              labels={'status': lambda r: r.status_code})
        def test():
            return 'OK'

        self.app.register_blueprint(blueprint)
        self.metrics.init_app(self.app)

        self.client.get('/test')

        response = self.client.get('/metrics')
        self.assertEqual(response.status_code, 200)
        self.assertIn('requests_by_status_count{status="200"} 1.0', str(response.data))
        self.assertRegex(str(response.data), 'requests_by_status_sum{status="200"} [0-9.]+') 
Example #14
Source File: routes.py    From fuzz-lightyear with Apache License 2.0 6 votes vote down vote up
def configure_routes(app):
    blueprint = Blueprint('api', __name__)
    api.init_app(blueprint)

    for module_name in views.__all__:
        module = import_module(
            '.views.{}'.format(module_name),
            package='testing.vulnerable_app',
        )

        api.add_namespace(module.ns)

    app.register_blueprint(blueprint)

    app.route('/schema')(_get_schema)
    app.route('/shutdown', methods=['POST'])(_shutdown) 
Example #15
Source File: __init__.py    From flaskapp with MIT License 6 votes vote down vote up
def __register_blueprint_models():
    # 注册模块信息
    try:
        from .views import BLUEPRINT_MODELS
        if not isinstance(BLUEPRINT_MODELS, (tuple, list, set)):
            raise AssertionError('BLUEPRINT_MODELS must be (tuple, list, set) type.')
    except (ImportError, AssertionError, Exception) as e:
        logger.warning('register blueprint fail, {}'.format(e))
        return

    for model in BLUEPRINT_MODELS:
        if not isinstance(model, Blueprint):
            logger.error('Register Blueprint {} model fail, '
                         'The model type must be flask.Blueprint.'.format(model))
            continue
        try:
            app.register_blueprint(model)
            logger.info('register blueprint {} success.'.format(model.name))
        except Exception as e:
            logger.error('register blueprint {} error, {}.'.format(model.name, e)) 
Example #16
Source File: __init__.py    From flask-restless-swagger with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def init_app(self, app, **kwargs):
        self.app = app
        self.manager = APIManager(self.app, **kwargs)

        swagger = Blueprint('swagger', __name__, static_folder='static',
                            static_url_path=self.app.static_url_path + '/swagger', )

        @swagger.route('/swagger')
        def swagger_ui():
            return redirect('/static/swagger/swagger-ui/index.html')

        @swagger.route('/swagger.json')
        def swagger_json():
            # I can only get this from a request context
            self.swagger['host'] = urlparse.urlparse(request.url_root).netloc
            return jsonify(self.swagger)

        app.register_blueprint(swagger) 
Example #17
Source File: blueprints.py    From Flask-P2P with MIT License 6 votes vote down vote up
def test_blueprint_url_definitions(self):
        bp = flask.Blueprint('test', __name__)

        @bp.route('/foo', defaults={'baz': 42})
        def foo(bar, baz):
            return '%s/%d' % (bar, baz)

        @bp.route('/bar')
        def bar(bar):
            return text_type(bar)

        app = flask.Flask(__name__)
        app.register_blueprint(bp, url_prefix='/1', url_defaults={'bar': 23})
        app.register_blueprint(bp, url_prefix='/2', url_defaults={'bar': 19})

        c = app.test_client()
        self.assert_equal(c.get('/1/foo').data, b'23/42')
        self.assert_equal(c.get('/2/foo').data, b'19/42')
        self.assert_equal(c.get('/1/bar').data, b'23')
        self.assert_equal(c.get('/2/bar').data, b'19') 
Example #18
Source File: blueprints.py    From Flask-P2P with MIT License 6 votes vote down vote up
def test_default_static_cache_timeout(self):
        app = flask.Flask(__name__)
        class MyBlueprint(flask.Blueprint):
            def get_send_file_max_age(self, filename):
                return 100

        blueprint = MyBlueprint('blueprint', __name__, static_folder='static')
        app.register_blueprint(blueprint)

        # try/finally, in case other tests use this app for Blueprint tests.
        max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT']
        try:
            with app.test_request_context():
                unexpected_max_age = 3600
                if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == unexpected_max_age:
                    unexpected_max_age = 7200
                app.config['SEND_FILE_MAX_AGE_DEFAULT'] = unexpected_max_age
                rv = blueprint.send_static_file('index.html')
                cc = parse_cache_control_header(rv.headers['Cache-Control'])
                self.assert_equal(cc.max_age, 100)
                rv.close()
        finally:
            app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default 
Example #19
Source File: blueprints.py    From Flask-P2P with MIT License 6 votes vote down vote up
def test_dotted_names_from_app(self):
        app = flask.Flask(__name__)
        app.testing = True
        test = flask.Blueprint('test', __name__)

        @app.route('/')
        def app_index():
            return flask.url_for('test.index')

        @test.route('/test/')
        def index():
            return flask.url_for('app_index')

        app.register_blueprint(test)

        with app.test_client() as c:
            rv = c.get('/')
            self.assert_equal(rv.data, b'/test/') 
Example #20
Source File: basic.py    From Flask-P2P with MIT License 6 votes vote down vote up
def test_inject_blueprint_url_defaults(self):
        app = flask.Flask(__name__)
        bp = flask.Blueprint('foo.bar.baz', __name__,
                       template_folder='template')

        @bp.url_defaults
        def bp_defaults(endpoint, values):
            values['page'] = 'login'
        @bp.route('/<page>')
        def view(page): pass

        app.register_blueprint(bp)

        values = dict()
        app.inject_url_defaults('foo.bar.baz.view', values)
        expected = dict(page='login')
        self.assert_equal(values, expected)

        with app.test_request_context('/somepage'):
            url = flask.url_for('foo.bar.baz.view')
        expected = '/login'
        self.assert_equal(url, expected) 
Example #21
Source File: idp.py    From flask-saml2 with MIT License 6 votes vote down vote up
def create_blueprint(self):
        """Create a blueprint for this IdP.
        This blueprint needs to be registered with a Flask application
        to expose the IdP functionality.
        """
        bp = Blueprint(self.blueprint_name, 'flask_saml2.idp', template_folder='templates')

        bp.add_url_rule('/login/', view_func=LoginBegin.as_view(
            'login_begin', idp=self))
        bp.add_url_rule('/login/process/', view_func=LoginProcess.as_view(
            'login_process', idp=self))

        bp.add_url_rule('/logout/', view_func=Logout.as_view(
            'logout', idp=self))

        bp.add_url_rule('/metadata.xml', view_func=Metadata.as_view(
            'metadata', idp=self))

        bp.register_error_handler(CannotHandleAssertion, CannotHandleAssertionView.as_view(
            'cannot_handle_assertion', idp=self))
        bp.register_error_handler(UserNotAuthorized, UserNotAuthorizedView.as_view(
            'user_not_authorized', idp=self))

        return bp 
Example #22
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 #23
Source File: link.py    From fence with Apache License 2.0 5 votes vote down vote up
def make_link_blueprint():
    """
    Return:
        flask.Blueprint: the blueprint used for ``/link`` endpoints
    """
    blueprint = flask.Blueprint("link", __name__)
    blueprint_api = RestfulApi(blueprint)

    if config["ALLOW_GOOGLE_LINKING"]:
        blueprint_api.add_resource(GoogleLinkRedirect, "/google", strict_slashes=False)
        blueprint_api.add_resource(
            GoogleCallback, "/google/callback", strict_slashes=False
        )

    return blueprint 
Example #24
Source File: stocks_api.py    From stockreader with MIT License 5 votes vote down vote up
def get_stocks_blueprint(domain, job, time_series):
    stocks_blueprint = Blueprint('stocks_api', __name__)

    @stocks_blueprint.route('', methods=['POST'])
    def add_stock():
        response = None
        new_stock = request.get_json()
        logger.info("post: %s", new_stock)
        if new_stock is None:
            response = jsonify({ "error": "Please provide a stock in the request body. It should have a name, a symbol and a stock market" }), 400
            return response
        name = new_stock.get("name", None)
        quote = new_stock.get("symbol", None)
        stock_market = new_stock.get("stockMarket", None)
        is_valid_stock = name and quote and stock_market
        if not is_valid_stock:
            response = jsonify({ "error": "Please provide a valid stock. It should have a name, a symbol and a stock market" }), 400
            return response
        # This validation (stockExistInDB) should be performed in the domain level, not in the API level.
        stock_exist_in_db = domain.stock_exists(quote)
        if stock_exist_in_db:
            response = jsonify({ "error": "The given stock already exists" }), 409
            return response
        # Add stock async
        time_series.save_async("API", {}, { "method": "add_stock", "stock": quote })
        thread = threading.Thread(target=job.add_stock_to_stockreader, args=(new_stock,)) # Why args should be a tuple?
        thread.start()
        response = jsonify({ "success": "The stock " + quote + " is being added" }), 202
        return response

    return stocks_blueprint 
Example #25
Source File: blueprints.py    From Flask-P2P with MIT License 5 votes vote down vote up
def test_blueprint_url_processors(self):
        bp = flask.Blueprint('frontend', __name__, url_prefix='/<lang_code>')

        @bp.url_defaults
        def add_language_code(endpoint, values):
            values.setdefault('lang_code', flask.g.lang_code)

        @bp.url_value_preprocessor
        def pull_lang_code(endpoint, values):
            flask.g.lang_code = values.pop('lang_code')

        @bp.route('/')
        def index():
            return flask.url_for('.about')

        @bp.route('/about')
        def about():
            return flask.url_for('.index')

        app = flask.Flask(__name__)
        app.register_blueprint(bp)

        c = app.test_client()

        self.assert_equal(c.get('/de/').data, b'/de/about')
        self.assert_equal(c.get('/de/about').data, b'/de/') 
Example #26
Source File: test_blueprints.py    From Flask-Large-Application-Example with MIT License 5 votes vote down vote up
def test_blueprint_instances():
    assert all([isinstance(bp, Blueprint) for bp in all_blueprints])
    assert len(all_blueprints) == len(set([bp.url_prefix for bp in all_blueprints if bp.url_prefix]))
    assert all([b.import_name.startswith('pypi_portal.views.') for b in all_blueprints]) 
Example #27
Source File: blueprints.py    From Flask-P2P with MIT License 5 votes vote down vote up
def test_empty_url_defaults(self):
        bp = flask.Blueprint('bp', __name__)

        @bp.route('/', defaults={'page': 1})
        @bp.route('/page/<int:page>')
        def something(page):
            return str(page)

        app = flask.Flask(__name__)
        app.register_blueprint(bp)

        c = app.test_client()
        self.assert_equal(c.get('/').data, b'1')
        self.assert_equal(c.get('/page/2').data, b'2') 
Example #28
Source File: blueprints.py    From Flask-P2P with MIT License 5 votes vote down vote up
def test_route_decorator_custom_endpoint(self):

        bp = flask.Blueprint('bp', __name__)

        @bp.route('/foo')
        def foo():
            return flask.request.endpoint

        @bp.route('/bar', endpoint='bar')
        def foo_bar():
            return flask.request.endpoint

        @bp.route('/bar/123', endpoint='123')
        def foo_bar_foo():
            return flask.request.endpoint

        @bp.route('/bar/foo')
        def bar_foo():
            return flask.request.endpoint

        app = flask.Flask(__name__)
        app.register_blueprint(bp, url_prefix='/py')

        @app.route('/')
        def index():
            return flask.request.endpoint

        c = app.test_client()
        self.assertEqual(c.get('/').data, b'index')
        self.assertEqual(c.get('/py/foo').data, b'bp.foo')
        self.assertEqual(c.get('/py/bar').data, b'bp.bar')
        self.assertEqual(c.get('/py/bar/123').data, b'bp.123')
        self.assertEqual(c.get('/py/bar/foo').data, b'bp.bar_foo') 
Example #29
Source File: blueprints.py    From Flask-P2P with MIT License 5 votes vote down vote up
def test_template_filter(self):
        bp = flask.Blueprint('bp', __name__)
        @bp.app_template_filter()
        def my_reverse(s):
            return s[::-1]
        app = flask.Flask(__name__)
        app.register_blueprint(bp, url_prefix='/py')
        self.assert_in('my_reverse', app.jinja_env.filters.keys())
        self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse)
        self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba') 
Example #30
Source File: blueprints.py    From Flask-P2P with MIT License 5 votes vote down vote up
def test_blueprint_specific_error_handling(self):
        frontend = flask.Blueprint('frontend', __name__)
        backend = flask.Blueprint('backend', __name__)
        sideend = flask.Blueprint('sideend', __name__)

        @frontend.errorhandler(403)
        def frontend_forbidden(e):
            return 'frontend says no', 403

        @frontend.route('/frontend-no')
        def frontend_no():
            flask.abort(403)

        @backend.errorhandler(403)
        def backend_forbidden(e):
            return 'backend says no', 403

        @backend.route('/backend-no')
        def backend_no():
            flask.abort(403)

        @sideend.route('/what-is-a-sideend')
        def sideend_no():
            flask.abort(403)

        app = flask.Flask(__name__)
        app.register_blueprint(frontend)
        app.register_blueprint(backend)
        app.register_blueprint(sideend)

        @app.errorhandler(403)
        def app_forbidden(e):
            return 'application itself says no', 403

        c = app.test_client()

        self.assert_equal(c.get('/frontend-no').data, b'frontend says no')
        self.assert_equal(c.get('/backend-no').data, b'backend says no')
        self.assert_equal(c.get('/what-is-a-sideend').data, b'application itself says no')