本文整理汇总了Python中flask.Blueprint方法的典型用法代码示例。如果您正苦于以下问题:Python flask.Blueprint方法的具体用法?Python flask.Blueprint怎么用?Python flask.Blueprint使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flask
的用法示例。
在下文中一共展示了flask.Blueprint方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _factory
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Blueprint [as 别名]
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
示例2: route
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Blueprint [as 别名]
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
示例3: exempt
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Blueprint [as 别名]
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
示例4: create_app
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Blueprint [as 别名]
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
示例5: _factory
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Blueprint [as 别名]
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
示例6: add_swagger_routes
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Blueprint [as 别名]
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)
示例7: test_deferred_register
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Blueprint [as 别名]
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
示例8: blueprint
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Blueprint [as 别名]
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
示例9: load_plugin
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Blueprint [as 别名]
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
示例10: _register_doc_blueprint
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Blueprint [as 别名]
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)
示例11: __init__
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Blueprint [as 别名]
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)
示例12: register_api
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Blueprint [as 别名]
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)
示例13: test_i18n_alternate_links_outside_i18n_blueprint
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Blueprint [as 别名]
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''
示例14: create_blueprint
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Blueprint [as 别名]
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
示例15: test_blueprint
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Blueprint [as 别名]
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.]+')