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


Python response.HTTPResponse方法代碼示例

本文整理匯總了Python中sanic.response.HTTPResponse方法的典型用法代碼示例。如果您正苦於以下問題:Python response.HTTPResponse方法的具體用法?Python response.HTTPResponse怎麽用?Python response.HTTPResponse使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在sanic.response的用法示例。


在下文中一共展示了response.HTTPResponse方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_with_middleware_response

# 需要導入模塊: from sanic import response [as 別名]
# 或者: from sanic.response import HTTPResponse [as 別名]
def test_with_middleware_response(app):
    results = []

    @app.middleware("request")
    async def process_request(request):
        results.append(request)

    @app.middleware("response")
    async def process_response(request, response):
        results.append(request)
        results.append(response)

    class DummyView(HTTPMethodView):
        def get(self, request):
            return text("I am get method")

    app.add_route(DummyView.as_view(), "/")

    request, response = app.test_client.get("/")

    assert response.text == "I am get method"
    assert type(results[0]) is Request
    assert type(results[1]) is Request
    assert isinstance(results[2], HTTPResponse) 
開發者ID:huge-success,項目名稱:sanic,代碼行數:26,代碼來源:test_views.py

示例2: test_middleware_response

# 需要導入模塊: from sanic import response [as 別名]
# 或者: from sanic.response import HTTPResponse [as 別名]
def test_middleware_response(app):
    results = []

    @app.middleware("request")
    async def process_request(request):
        results.append(request)

    @app.middleware("response")
    async def process_response(request, response):
        results.append(request)
        results.append(response)

    @app.route("/")
    async def handler(request):
        return text("OK")

    request, response = app.test_client.get("/")

    assert response.text == "OK"
    assert type(results[0]) is Request
    assert type(results[1]) is Request
    assert isinstance(results[2], HTTPResponse) 
開發者ID:huge-success,項目名稱:sanic,代碼行數:24,代碼來源:test_middleware.py

示例3: process_preflight

# 需要導入模塊: from sanic import response [as 別名]
# 或者: from sanic.response import HTTPResponse [as 別名]
def process_preflight(self, request):
        """ Preflight request support for apollo-client
        https://www.w3.org/TR/cors/#resource-preflight-requests """
        origin = request.headers.get("Origin", "")
        method = request.headers.get("Access-Control-Request-Method", "").upper()

        if method and method in self.methods:
            return HTTPResponse(
                status=200,
                headers={
                    "Access-Control-Allow-Origin": origin,
                    "Access-Control-Allow-Methods": ", ".join(self.methods),
                    "Access-Control-Max-Age": str(self.max_age),
                },
            )
        else:
            return HTTPResponse(status=400) 
開發者ID:graphql-python,項目名稱:graphql-server-core,代碼行數:19,代碼來源:graphqlview.py

示例4: add_swagger_api_route

# 需要導入模塊: from sanic import response [as 別名]
# 或者: from sanic.response import HTTPResponse [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

示例5: create_swagger_json_handler

# 需要導入模塊: from sanic import response [as 別名]
# 或者: from sanic.response import HTTPResponse [as 別名]
def create_swagger_json_handler(app, **kwargs):
    """
    Create a handler that returns the swagger definition
    for an application.
    This method assumes the application is using the
    TransmuteUrlDispatcher as the router.
    """

    spec = get_swagger_spec(app)
    _add_blueprint_specs(app, spec)
    spec_dict = spec.swagger_definition(**kwargs)
    encoded_spec = json.dumps(spec_dict).encode("UTF-8")

    async def swagger(request):
        return HTTPResponse(
            body_bytes=encoded_spec,
            headers={
                "Access-Control-Allow-Origin": "*"
            },
            content_type="application/json",
        )

    return swagger 
開發者ID:yunstanford,項目名稱:sanic-transmute,代碼行數:25,代碼來源:swagger.py

示例6: setUp

# 需要導入模塊: from sanic import response [as 別名]
# 或者: from sanic.response import HTTPResponse [as 別名]
def setUp(self):
        self.app = Sanic(__name__)

        @self.app.route('/', methods=['GET', 'HEAD', 'OPTIONS'])
        @cross_origin(self.app)
        def wildcard(request):
            return text('Welcome!')

        @self.app.route('/test_consistent_origin', methods=['GET', 'HEAD', 'OPTIONS'])
        @cross_origin(self.app, origins='http://foo.com')
        def test_consistent(request):
            return text('Welcome!')

        @self.app.route('/test_vary', methods=['GET', 'HEAD', 'OPTIONS'])
        @cross_origin(self.app, origins=["http://foo.com", "http://bar.com"])
        def test_vary(request):
            return text('Welcome!')

        @self.app.route('/test_existing_vary_headers')
        @cross_origin(self.app, origins=["http://foo.com", "http://bar.com"])
        def test_existing_vary_headers(request):
            return HTTPResponse('', status=200, headers=CIMultiDict({'Vary': 'Accept-Encoding'})) 
開發者ID:ashleysommer,項目名稱:sanic-cors,代碼行數:24,代碼來源:test_vary_header.py

示例7: test_middleware_response

# 需要導入模塊: from sanic import response [as 別名]
# 或者: from sanic.response import HTTPResponse [as 別名]
def test_middleware_response():
    app = Sanic('test_middleware_response')

    results = []

    @app.middleware('request')
    async def process_response(request):
        results.append(request)

    @app.middleware('response')
    async def process_response(request, response):
        results.append(request)
        results.append(response)

    @app.route('/')
    async def handler(request):
        return text('OK')

    request, response = sanic_endpoint_test(app)

    assert response.text == 'OK'
    assert type(results[0]) is Request
    assert type(results[1]) is Request
    assert issubclass(type(results[2]), HTTPResponse) 
開發者ID:hhstore,項目名稱:annotated-py-projects,代碼行數:26,代碼來源:test_middleware.py

示例8: blueprint

# 需要導入模塊: from sanic import response [as 別名]
# 或者: from sanic.response import HTTPResponse [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_on_response_normal_http_response

# 需要導入模塊: from sanic import response [as 別名]
# 或者: from sanic.response import HTTPResponse [as 別名]
def test_on_response_normal_http_response():
    class MockRequest:
        method = 'GET'
        url = 'http://localhost'

    req = MockRequest()
    resp = HTTPResponse()

    contextvars.bind_contextvars(
        request_id='test-request',
    )
    ctx = contextvars._get_context()
    assert 'test-request' == ctx.get('request_id')

    app.on_response(req, resp)

    ctx = contextvars._get_context()
    assert ctx.get('request_id') is None 
開發者ID:vapor-ware,項目名稱:synse-server,代碼行數:20,代碼來源:test_app.py

示例10: on_response

# 需要導入模塊: from sanic import response [as 別名]
# 或者: from sanic.response import HTTPResponse [as 別名]
def on_response(request: Request, response: HTTPResponse) -> None:
    """Middleware function that runs prior to returning a response via Sanic."""

    # Default bytes. If this is a StreamingHTTPResponse, this value is
    # used, since there is no response.body for those responses.
    # (https://github.com/vapor-ware/synse-server/issues/396)
    byte_count = -1
    if hasattr(response, 'body') and response.body is not None:
        byte_count = len(response.body)

    logger.debug(
        'returning HTTP response',
        request=f'{request.method} {request.url}',
        status=response.status,
        bytes=byte_count,
    )

    # Unbind the request ID from the logger.
    contextvars.unbind_contextvars(
        'request_id',
    ) 
開發者ID:vapor-ware,項目名稱:synse-server,代碼行數:23,代碼來源:app.py

示例11: test

# 需要導入模塊: from sanic import response [as 別名]
# 或者: from sanic.response import HTTPResponse [as 別名]
def test(request: Request) -> HTTPResponse:
    """A dependency and side-effect free check to see whether Synse Server
    is reachable and responsive.

    This endpoint does not have any internal data dependencies. A failure
    may indicate that Synse Server is not serving (e.g. still starting up
    or experiencing a failure), or that it is not reachable on the network.

    Args:
        request: The Sanic request object.

    Returns:
        A JSON-formatted HTTP response with the possible statuses:
          * 200: OK
          * 500: Catchall processing error
    """
    return utils.http_json_response(
        await cmd.test(),
    ) 
開發者ID:vapor-ware,項目名稱:synse-server,代碼行數:21,代碼來源:http.py

示例12: version

# 需要導入模塊: from sanic import response [as 別名]
# 或者: from sanic.response import HTTPResponse [as 別名]
def version(request: Request) -> HTTPResponse:
    """Get the version information for the Synse Server instance.

    The API version provided by this endpoint should be used in subsequent
    versioned requests to the instance.

    Args:
        request: The Sanic request object.

    Returns:
        A JSON-formatted HTTP response with the possible statuses:
          * 200: OK
          * 500: Catchall processing error
    """
    try:
        return utils.http_json_response(
            await cmd.version(),
        )
    except Exception:
        logger.exception('failed to get version info')
        raise 
開發者ID:vapor-ware,項目名稱:synse-server,代碼行數:23,代碼來源:http.py

示例13: plugins

# 需要導入模塊: from sanic import response [as 別名]
# 或者: from sanic.response import HTTPResponse [as 別名]
def plugins(request: Request) -> HTTPResponse:
    """Get a summary of all the plugins currently registered with Synse Server.

    Args:
        request: The Sanic request object.

    Returns:
        A JSON-formatted HTTP response with the possible statuses:
          * 200: OK
          * 500: Catchall processing error
    """
    refresh = request.args.get('refresh', 'false').lower() == 'true'

    try:
        return utils.http_json_response(
            await cmd.plugins(
                refresh=refresh,
            ),
        )
    except Exception:
        logger.exception('failed to get plugins')
        raise 
開發者ID:vapor-ware,項目名稱:synse-server,代碼行數:24,代碼來源:http.py

示例14: plugin_info

# 需要導入模塊: from sanic import response [as 別名]
# 或者: from sanic.response import HTTPResponse [as 別名]
def plugin_info(request: Request, plugin_id: str) -> HTTPResponse:
    """Get detailed information on the specified plugin.

    Args:
        request: The Sanic request object.
        plugin_id: The ID of the plugin to get information for.

    Returns:
        A JSON-formatted HTTP response with the possible statuses:
          * 200: OK
          * 404: Plugin not found
          * 500: Catchall processing error
    """
    try:
        return utils.http_json_response(
            await cmd.plugin(plugin_id),
        )
    except Exception:
        logger.exception('failed to get plugin info', id=plugin_id)
        raise 
開發者ID:vapor-ware,項目名稱:synse-server,代碼行數:22,代碼來源:http.py

示例15: plugin_health

# 需要導入模塊: from sanic import response [as 別名]
# 或者: from sanic.response import HTTPResponse [as 別名]
def plugin_health(request: Request) -> HTTPResponse:
    """Get a summary of the health of registered plugins.

    Args:
        request: The Sanic request object.

    Returns:
        A JSON-formatted HTTP response with the possible statuses:
          * 200: OK
          * 500: Catchall processing error
    """
    try:
        return utils.http_json_response(
            await cmd.plugin_health(),
        )
    except Exception:
        logger.exception('failed to get plugin health')
        raise 
開發者ID:vapor-ware,項目名稱:synse-server,代碼行數:20,代碼來源:http.py


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