當前位置: 首頁>>代碼示例>>Python>>正文


Python sanic.Blueprint方法代碼示例

本文整理匯總了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). 
開發者ID:huge-success,項目名稱:sanic,代碼行數:24,代碼來源:test_multiprocessing.py

示例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) 
開發者ID:yunstanford,項目名稱:sanic-transmute,代碼行數:23,代碼來源:swagger.py

示例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"] 
開發者ID:huge-success,項目名稱:sanic-openapi,代碼行數:18,代碼來源:test_swagger.py

示例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) 
開發者ID:ahopkins,項目名稱:sanic-jwt,代碼行數:26,代碼來源:conftest.py

示例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 
開發者ID:ahopkins,項目名稱:sanic-jwt,代碼行數:18,代碼來源:test_initialize.py

示例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) 
開發者ID:ahopkins,項目名稱:sanic-jwt,代碼行數:22,代碼來源:initialization.py

示例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() 
開發者ID:ahopkins,項目名稱:sanic-jwt,代碼行數:25,代碼來源:initialization.py

示例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 
開發者ID:botfront,項目名稱:rasa-for-botfront,代碼行數:23,代碼來源:callback.py

示例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) 
開發者ID:bohea,項目名稱:sanic-limiter,代碼行數:18,代碼來源:test_extension.py

示例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) 
開發者ID:ashleysommer,項目名稱:sanicpluginsframework,代碼行數:23,代碼來源:framework.py

示例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) 
開發者ID:ashleysommer,項目名稱:sanicpluginsframework,代碼行數:23,代碼來源:framework.py

示例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)) 
開發者ID:ashleysommer,項目名稱:sanicpluginsframework,代碼行數:24,代碼來源:framework.py

示例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" 
開發者ID:huge-success,項目名稱:sanic,代碼行數:15,代碼來源:test_requests.py

示例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" 
開發者ID:huge-success,項目名稱:sanic,代碼行數:15,代碼來源:test_requests.py

示例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" 
開發者ID:huge-success,項目名稱:sanic,代碼行數:13,代碼來源:test_multiprocessing.py


注:本文中的sanic.Blueprint方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。