本文整理汇总了Python中sanic.Blueprint方法的典型用法代码示例。如果您正苦于以下问题:Python sanic.Blueprint方法的具体用法?Python sanic.Blueprint怎么用?Python sanic.Blueprint使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sanic
的用法示例。
在下文中一共展示了sanic.Blueprint方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_multiprocessing_with_blueprint
# 需要导入模块: import sanic [as 别名]
# 或者: from sanic import Blueprint [as 别名]
def test_multiprocessing_with_blueprint(app):
# Selects a number at random so we can spot check
num_workers = random.choice(range(2, multiprocessing.cpu_count() * 2 + 1))
process_list = set()
def stop_on_alarm(*args):
for process in multiprocessing.active_children():
process_list.add(process.pid)
process.terminate()
signal.signal(signal.SIGALRM, stop_on_alarm)
signal.alarm(3)
bp = Blueprint("test_text")
app.blueprint(bp)
app.run(HOST, PORT, workers=num_workers)
assert len(process_list) == num_workers
# this function must be outside a test function so that it can be
# able to be pickled (local functions cannot be pickled).
示例2: add_swagger_api_route
# 需要导入模块: import sanic [as 别名]
# 或者: from sanic import Blueprint [as 别名]
def add_swagger_api_route(app, target_route, swagger_json_route):
"""
mount a swagger statics page.
app: the sanic app object
target_route: the path to mount the statics page.
swagger_json_route: the path where the swagger json definitions is
expected to be.
"""
static_root = get_swagger_static_root()
swagger_body = generate_swagger_html(
STATIC_ROOT, swagger_json_route
).encode("utf-8")
async def swagger_ui(request):
return HTTPResponse(body_bytes=swagger_body, content_type="text/html")
bp = Blueprint('swagger')
bp.static(STATIC_ROOT, static_root)
app.add_route(swagger_ui, target_route, methods=["GET"])
app.blueprint(bp)
示例3: test_blueprint_class_based_view
# 需要导入模块: import sanic [as 别名]
# 或者: from sanic import Blueprint [as 别名]
def test_blueprint_class_based_view(app):
bp = Blueprint("test")
bp.add_route(SimpleView.as_view(), "/")
app.blueprint(bp)
_, response = app.test_client.get("/swagger/swagger.json")
assert response.status == 200
assert response.content_type == "application/json"
swagger_json = response.json
methods = METHODS.copy()
methods.remove("options")
assert sorted(set(methods)) == sorted(set(swagger_json["paths"]["/"].keys()))
assert {"name": "test"} in swagger_json["tags"]
示例4: app_with_bp_setup_without_init
# 需要导入模块: import sanic [as 别名]
# 或者: from sanic import Blueprint [as 别名]
def app_with_bp_setup_without_init(username_table, authenticate):
sanic_app = Sanic("sanic-jwt-test")
@sanic_app.route("/")
async def helloworld(request):
return json({"hello": "world"})
@sanic_app.route("/protected")
@protected()
async def protected_request(request):
return json({"protected": True})
sanic_bp = Blueprint("bp", url_prefix="/bp")
@sanic_bp.route("/")
async def bp_helloworld(request):
return json({"hello": "world"})
@sanic_bp.route("/protected")
@protected()
async def bp_protected_request(request):
return json({"protected": True})
yield (sanic_app, sanic_bp)
示例5: test_initialize_app_and_bp
# 需要导入模块: import sanic [as 别名]
# 或者: from sanic import Blueprint [as 别名]
def test_initialize_app_and_bp():
app = Sanic("sanic-jwt-test")
bp = Blueprint("bp", url_prefix="/bpapi")
Initialize(instance=bp, app=app, authenticate=lambda: True)
app.blueprint(bp)
# print("app", app.router.routes_all.keys())
# print("bp", [x.uri for x in bp.routes])
# Result:
# assert False
示例6: __add_endpoints
# 需要导入模块: import sanic [as 别名]
# 或者: from sanic import Blueprint [as 别名]
def __add_endpoints(self):
"""
Initialize the Sanic JWT Blueprint and add to the instance initialized
"""
for mapping in endpoint_mappings:
if all(map(self.config.get, mapping.keys)):
self.__add_single_endpoint(
mapping.cls,
mapping.endpoint,
mapping.is_protected,
mapping.protected_kwargs,
)
self.bp.exception(exceptions.SanicJWTException)(
self.responses.exception_response
)
if not self.instance_is_blueprint:
url_prefix = self._get_url_prefix()
self.instance.blueprint(self.bp, url_prefix=url_prefix)
示例7: __add_class_views
# 需要导入模块: import sanic [as 别名]
# 或者: from sanic import Blueprint [as 别名]
def __add_class_views(self):
"""
Include any custom class views on the Sanic JWT Blueprint
"""
config = self.config
if "class_views" in self.kwargs:
class_views = self.kwargs.pop("class_views")
for route, view in class_views:
if issubclass(view, endpoints.BaseEndpoint) and isinstance(
route, str
):
self.bp.add_route(
view.as_view(
self.responses,
config=self.config,
instance=self.instance,
),
route,
strict_slashes=config.strict_slashes(),
)
else:
raise exceptions.InvalidClassViewsFormat()
示例8: blueprint
# 需要导入模块: import sanic [as 别名]
# 或者: from sanic import Blueprint [as 别名]
def blueprint(
self, on_new_message: Callable[[UserMessage], Awaitable[Any]]
) -> Blueprint:
callback_webhook = Blueprint("callback_webhook", __name__)
@callback_webhook.route("/", methods=["GET"])
async def health(_: Request):
return response.json({"status": "ok"})
@callback_webhook.route("/webhook", methods=["POST"])
async def webhook(request: Request) -> HTTPResponse:
sender_id = await self._extract_sender(request)
text = self._extract_message(request)
collector = self.get_output_channel()
await on_new_message(
UserMessage(text, collector, sender_id, input_channel=self.name())
)
return response.text("success")
return callback_webhook
示例9: test_bp_combined_limit
# 需要导入模块: import sanic [as 别名]
# 或者: from sanic import Blueprint [as 别名]
def test_bp_combined_limit(self):
app, limiter = self.build_app(config={}, global_limits=['1/day'])
bp = Blueprint('/bp')
limiter.limit('1 per hour')(bp)
@bp.route("/bp1")
@limiter.limit('2 per hour')
async def bp_t1(request):
return text("bp_t1")
app.blueprint(bp)
cli = app.test_client
self.assertEqual(200, cli.get("/bp1")[1].status)
self.assertEqual(200, cli.get("/bp1")[1].status)
self.assertEqual(429, cli.get("/bp1")[1].status)
示例10: _register_route_helper
# 需要导入模块: import sanic [as 别名]
# 或者: from sanic import Blueprint [as 别名]
def _register_route_helper(r, _spf, plugin, context, _p_name,
_url_prefix):
# Prepend the plugin URI prefix if available
uri = _url_prefix + r.uri if _url_prefix else r.uri
uri = uri[1:] if uri.startswith('//') else uri
# attach the plugin name to the handler so that it can be
# prefixed properly in the router
_app = _spf._app
if isinstance(_app, Blueprint):
# blueprint always handles adding __blueprintname__
# So we identify ourselves here a different way.
handler_name = r.handler.__name__
r.handler.__name__ = "{}.{}".format(_p_name, handler_name)
_spf._plugin_register_bp_route(
r.handler, plugin, context, uri, *r.args, **r.kwargs)
else:
# app is not a blueprint, but we use the __blueprintname__
# property to store the plugin name
r.handler.__blueprintname__ = _p_name
_spf._plugin_register_app_route(
r.handler, plugin, context, uri, *r.args, **r.kwargs)
示例11: _register_websocket_route_helper
# 需要导入模块: import sanic [as 别名]
# 或者: from sanic import Blueprint [as 别名]
def _register_websocket_route_helper(w, _spf, plugin, context, _p_name,
_url_prefix):
# Prepend the plugin URI prefix if available
uri = _url_prefix + w.uri if _url_prefix else w.uri
uri = uri[1:] if uri.startswith('//') else uri
# attach the plugin name to the handler so that it can be
# prefixed properly in the router
_app = _spf._app
if isinstance(_app, Blueprint):
# blueprint always handles adding __blueprintname__
# So we identify ourselves here a different way.
handler_name = w.handler.__name__
w.handler.__name__ = "{}.{}".format(_p_name, handler_name)
_spf._plugin_register_bp_websocket_route(
w.handler, plugin, context, uri, *w.args, **w.kwargs)
else:
# app is not a blueprint, but we use the __blueprintname__
# property to store the plugin name
w.handler.__blueprintname__ = _p_name
_spf._plugin_register_app_websocket_route(
w.handler, plugin, context, uri, *w.args, **w.kwargs)
示例12: _on_server_start
# 需要导入模块: import sanic [as 别名]
# 或者: from sanic import Blueprint [as 别名]
def _on_server_start(self, app, loop):
if not isinstance(self._app, Blueprint):
assert self._app == app,\
"Sanic Plugins Framework is not assigned to the correct " \
"Sanic App!"
if self._running:
# during testing, this will be called _many_ times.
return # Ignore if this is already called.
self._loop = loop
self._running = True
# sort and freeze these
self._pre_request_middleware = \
tuple(sorted(self._pre_request_middleware))
self._post_request_middleware = \
tuple(sorted(self._post_request_middleware))
self._pre_response_middleware = \
tuple(sorted(self._pre_response_middleware))
self._post_response_middleware = \
tuple(sorted(self._post_response_middleware))
self._cleanup_middleware = \
tuple(sorted(self._cleanup_middleware))
示例13: test_endpoint_blueprint
# 需要导入模块: import sanic [as 别名]
# 或者: from sanic import Blueprint [as 别名]
def test_endpoint_blueprint():
bp = Blueprint("my_blueprint", url_prefix="/bp")
@bp.route("/")
async def bp_root(request):
return text("Hello")
app = Sanic("named")
app.blueprint(bp)
request, response = app.test_client.get("/bp")
assert request.endpoint == "named.my_blueprint.bp_root"
示例14: test_endpoint_blueprint_asgi
# 需要导入模块: import sanic [as 别名]
# 或者: from sanic import Blueprint [as 别名]
def test_endpoint_blueprint_asgi():
bp = Blueprint("my_blueprint", url_prefix="/bp")
@bp.route("/")
async def bp_root(request):
return text("Hello")
app = Sanic("named")
app.blueprint(bp)
request, response = await app.asgi_client.get("/bp")
assert request.endpoint == "named.my_blueprint.bp_root"
示例15: test_pickle_app_with_bp
# 需要导入模块: import sanic [as 别名]
# 或者: from sanic import Blueprint [as 别名]
def test_pickle_app_with_bp(app, protocol):
bp = Blueprint("test_text")
bp.route("/")(handler)
app.blueprint(bp)
p_app = pickle.dumps(app, protocol=protocol)
del app
up_p_app = pickle.loads(p_app)
assert up_p_app
request, response = up_p_app.test_client.get("/")
assert up_p_app.is_request_stream is False
assert response.text == "Hello"