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: 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 #3
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 #4
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 #5
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 #6
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 #7
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 #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: 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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
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 #20
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 #21
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 #22
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 #23
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 #24
Source File: test_extension.py    From flask-apispec with MIT License 5 votes vote down vote up
def test_deferred_register(self, app):
        blueprint = Blueprint('test', __name__)
        docs = FlaskApiSpec()

        @doc(tags=['band'])
        class BandResource(MethodResource):
            def get(self, **kwargs):
                return 'slowdive'

        blueprint.add_url_rule('/bands/<band_id>/', view_func=BandResource.as_view('band'))
        docs.register(BandResource, endpoint='band', blueprint=blueprint.name)

        app.register_blueprint(blueprint)
        docs.init_app(app)

        assert '/bands/{band_id}/' in docs.spec._paths 
Example #25
Source File: views.py    From invenio-app-ils with MIT License 5 votes vote down vote up
def create_document_stats_blueprint(app):
    """Create document stats blueprint."""
    blueprint = Blueprint("ils_document_stats", __name__, url_prefix="")
    endpoints = app.config.get("RECORDS_REST_ENDPOINTS", [])

    def register_view(pid_type):
        options = endpoints.get(pid_type, {})
        default_media_type = options.get("default_media_type", "")
        rec_serializers = options.get("record_serializers", {})
        serializers = {
            mime: obj_or_import_string(func)
            for mime, func in rec_serializers.items()
        }

        stats_view = DocumentStatsResource.as_view(
            DocumentStatsResource.view_name.format(pid_type),
            serializers=serializers,
            default_media_type=default_media_type,
        )
        blueprint.add_url_rule(
            "{0}/stats".format(options["item_route"]),
            view_func=stats_view,
            methods=["POST"],
        )

    register_view(DOCUMENT_PID_TYPE)
    register_view(EITEM_PID_TYPE)
    return blueprint 
Example #26
Source File: views.py    From invenio-app-ils with MIT License 5 votes vote down vote up
def create_circulation_stats_blueprint(app):
    """Add statistics views to the blueprint."""
    blueprint = Blueprint(
        "invenio_app_ils_circulation_stats", __name__, url_prefix=""
    )

    create_most_loaned_documents_view(blueprint, app)

    return blueprint 
Example #27
Source File: views.py    From invenio-app-ils with MIT License 5 votes vote down vote up
def create_relations_blueprint(app):
    """Add relations views to the blueprint."""

    def _add_resource_view(blueprint, pid_type, view_class):
        """Add a resource view for a rest endpoint."""
        endpoints = app.config.get("RECORDS_REST_ENDPOINTS", [])
        options = endpoints.get(pid_type, {})
        default_media_type = options.get("default_media_type", "")
        rec_serializers = options.get("record_serializers", {})
        serializers = {
            mime: obj_or_import_string(func)
            for mime, func in rec_serializers.items()
        }
        record_relations = view_class.as_view(
            view_class.view_name.format(pid_type),
            serializers=serializers,
            default_media_type=default_media_type,
        )
        blueprint.add_url_rule(
            "{0}/relations".format(options["item_route"]),
            view_func=record_relations,
            methods=["POST", "DELETE"],
        )

    bp = Blueprint("invenio_app_ils_relations", __name__, url_prefix="")

    _add_resource_view(bp, DOCUMENT_PID_TYPE, RecordRelationsResource)
    _add_resource_view(bp, SERIES_PID_TYPE, RecordRelationsResource)

    return bp 
Example #28
Source File: __init__.py    From age-of-empires-II-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_app(cfg):
        app = Flask(__name__)
        app.config.update(cfg)

        api_blueprint = Blueprint(API_PREFIX + "/", __name__)
        api = Api(api_blueprint, prefix="/" + API_PREFIX)

        add_routes(api)
        add_docs(app, SWAGGER_CONFIG, '../data/apispecs.yaml')
        app.register_blueprint(api_blueprint)
        db.init_app(app)

        return app 
Example #29
Source File: test_common.py    From flask-security with MIT License 5 votes vote down vote up
def test_authenticate_with_next_bp(app, client):
    api = Blueprint("api", __name__)

    @api.route("/info")
    def info():
        pass

    app.register_blueprint(api, url_prefix="/api")
    data = dict(email="matt@lp.com", password="password")
    response = client.post("/login?next=api.info", data=data, follow_redirects=False)
    assert response.status_code == 302
    assert "api/info" in response.location 
Example #30
Source File: __init__.py    From flask-smorest with MIT License 5 votes vote down vote up
def register_converter(self, converter, conv_type, conv_format=None):
        """Register custom path parameter converter

        :param BaseConverter converter: Converter
            Subclass of werkzeug's BaseConverter
        :param str conv_type: Parameter type
        :param str conv_format: Parameter format (optional)

        Example: ::

            # Register MongoDB's ObjectId converter in Flask application
            app.url_map.converters['objectid'] = ObjectIdConverter

            # Register converter in Api
            api.register_converter(ObjectIdConverter, 'string', 'ObjectID')

            @blp.route('/pets/{objectid:pet_id}')
                ...

            api.register_blueprint(blp)

        Once the converter is registered, all paths using it will have
        corresponding path parameter documented with the right type and format.

        Should be called before registering paths with
        :meth:`Blueprint.route <Blueprint.route>`.
        """
        self._converters.append((converter, conv_type, conv_format))
        # Register converter in spec if app is already initialized
        if self.spec is not None:
            self._register_converter(converter, conv_type, conv_format)