Python sanic.response.HTTPResponse() Examples

The following are 30 code examples of sanic.response.HTTPResponse(). 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 sanic.response , or try the search function .
Example #1
Source File: http.py    From synse-server with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #2
Source File: test_vary_header.py    From sanic-cors with MIT License 6 votes vote down vote up
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'})) 
Example #3
Source File: test_middleware.py    From annotated-py-projects with MIT License 6 votes vote down vote up
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) 
Example #4
Source File: callback.py    From rasa-for-botfront with Apache License 2.0 6 votes vote down vote up
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 
Example #5
Source File: test_app.py    From synse-server with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #6
Source File: app.py    From synse-server with GNU General Public License v3.0 6 votes vote down vote up
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',
    ) 
Example #7
Source File: http.py    From synse-server with GNU General Public License v3.0 6 votes vote down vote up
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(),
    ) 
Example #8
Source File: http.py    From synse-server with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #9
Source File: http.py    From synse-server with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #10
Source File: test_middleware.py    From sanic with MIT License 6 votes vote down vote up
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) 
Example #11
Source File: http.py    From synse-server with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #12
Source File: http.py    From synse-server with GNU General Public License v3.0 6 votes vote down vote up
def info(request: Request, device_id: str) -> HTTPResponse:
    """Get detailed information about the specified device.

    Args:
        request: The Sanic request object.
        device_id: The ID of the device to get information for.

    Returns:
        A JSON-formatted HTTP response with the possible statuses:
          * 200: OK
          * 404: Device not found
          * 500: Catchall processing error
    """
    try:
        return utils.http_json_response(
            await cmd.info(device_id),
        )
    except Exception:
        logger.exception('failed to get device info', id=device_id)
        raise 
Example #13
Source File: http.py    From synse-server with GNU General Public License v3.0 6 votes vote down vote up
def read_device(request: Request, device_id: str) -> HTTPResponse:
    """Read from the specified device.

    This endpoint is equivalent to the ``read`` endpoint, specifying the ID tag
    for the device.

    Args:
        request: The Sanic request object.
        device_id: The ID of the device to read.

    Returns:
        A JSON-formatted HTTP response with the possible statuses:
          * 200: OK
          * 404: Device not found
          * 405: Device does not support reading
          * 500: Catchall processing error
    """
    try:
        return utils.http_json_response(
            await cmd.read_device(device_id),
        )
    except Exception:
        logger.exception('failed to read device', id=device_id)
        raise 
Example #14
Source File: http.py    From synse-server with GNU General Public License v3.0 6 votes vote down vote up
def transactions(request: Request) -> HTTPResponse:
    """Get a list of all transactions currently being tracked by Synse Server.

    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.transactions(),
        )
    except Exception:
        logger.exception('failed to list transactions')
        raise 
Example #15
Source File: http.py    From synse-server with GNU General Public License v3.0 6 votes vote down vote up
def transaction(request: Request, transaction_id: str) -> HTTPResponse:
    """Get the status of a write transaction.

    Args:
        request: The Sanic request object.
        transaction_id: The ID of the write transaction to get the status of.

    Returns:
        A JSON-formatted HTTP response with the possible statuses:
          * 200: OK
          * 404: Transaction not found
          * 500: Catchall processing error
    """
    try:
        return utils.http_json_response(
            await cmd.transaction(transaction_id),
        )
    except Exception:
        logger.exception('failed to get transaction info', id=transaction_id)
        raise 
Example #16
Source File: errors.py    From synse-server with GNU General Public License v3.0 6 votes vote down vote up
def default(self, request: Request, exception: Exception) -> HTTPResponse:
        """The default error handler for exceptions.

        This handles errors which have no error handler assigned. Synse Server
        does not register any other custom error handlers, so all exceptions
        raised by the application will be caught and handled here.
        """
        logger.info('creating error response for request', error=exception)

        if isinstance(exception, SanicException):
            return super(SynseErrorHandler, self).default(request, exception)

        if not isinstance(exception, SynseError):
            # Setting __cause__ on the exception is effectively the same
            # as what happens when you `raise NewException() from old_exception
            new = SynseError(str(exception))
            new.__cause__ = exception
            exception = new

        return utils.http_json_response(
            body=exception.make_response(),
            status=exception.http_code,
        ) 
Example #17
Source File: test_plugin_middleware.py    From sanicpluginsframework with MIT License 6 votes vote down vote up
def test_middleware_response(spf):
    app = spf._app
    plugin = TestPlugin()
    results = []

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

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

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

    spf.register_plugin(plugin)
    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) 
Example #18
Source File: test_views.py    From sanic with MIT License 6 votes vote down vote up
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) 
Example #19
Source File: swagger.py    From sanic-transmute with MIT License 6 votes vote down vote up
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 
Example #20
Source File: swagger.py    From sanic-transmute with MIT License 6 votes vote down vote up
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) 
Example #21
Source File: graphqlview.py    From graphql-server-core with MIT License 6 votes vote down vote up
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) 
Example #22
Source File: sanic.py    From python-engineio with MIT License 5 votes vote down vote up
def make_response(status, headers, payload, environ):  # pragma: no cover
    """This function generates an appropriate response object for this async
    mode.
    """
    headers_dict = {}
    content_type = None
    for h in headers:
        if h[0].lower() == 'content-type':
            content_type = h[1]
        else:
            headers_dict[h[0]] = h[1]
    return HTTPResponse(body_bytes=payload, content_type=content_type,
                        status=int(status.split()[0]), headers=headers_dict) 
Example #23
Source File: test_signal_handlers.py    From sanic with MIT License 5 votes vote down vote up
def test_register_system_signals(app):
    """Test if sanic register system signals"""

    @app.route("/hello")
    async def hello_route(request):
        return HTTPResponse()

    app.listener("after_server_start")(stop)
    app.listener("before_server_start")(set_loop)
    app.listener("after_server_stop")(after)

    app.run(HOST, PORT)
    assert calledq.get() is True 
Example #24
Source File: test_signal_handlers.py    From sanic with MIT License 5 votes vote down vote up
def test_dont_register_system_signals(app):
    """Test if sanic don't register system signals"""

    @app.route("/hello")
    async def hello_route(request):
        return HTTPResponse()

    app.listener("after_server_start")(stop)
    app.listener("before_server_start")(set_loop)
    app.listener("after_server_stop")(after)

    app.run(HOST, PORT, register_sys_signals=False)
    assert calledq.get() is False 
Example #25
Source File: server.py    From sanic with MIT License 5 votes vote down vote up
def log_response(self, response):
        """
        Helper method provided to enable the logging of responses in case if
        the :attr:`HttpProtocol.access_log` is enabled.

        :param response: Response generated for the current request

        :type response: :class:`sanic.response.HTTPResponse` or
            :class:`sanic.response.StreamingHTTPResponse`

        :return: None
        """
        if self.access_log:
            extra = {"status": getattr(response, "status", 0)}

            if isinstance(response, HTTPResponse):
                extra["byte"] = len(response.body)
            else:
                extra["byte"] = -1

            extra["host"] = "UNKNOWN"
            if self.request is not None:
                if self.request.ip:
                    extra["host"] = f"{self.request.ip}:{self.request.port}"

                extra["request"] = f"{self.request.method} {self.request.url}"
            else:
                extra["request"] = "nil"

            access_logger.info("", extra=extra) 
Example #26
Source File: http.py    From synse-server with GNU General Public License v3.0 5 votes vote down vote up
def tags(request: Request) -> HTTPResponse:
    """List all of the tags which are currently associated with devices
    in the system.

    By default, all non-ID tags are listed.

    Args:
        request: The Sanic request object.

    Query Parameters:
        ns: The tag namespace(s) to use when searching for tags. If specifying multiple
            namespaces, they can be passed in as a comma-separated list, e.g.
            ``?ns=ns1,ns2,ns3``, or via multiple ``ns`` parameters, e.g.
            ``?ns=ns1&ns=ns2&ns=ns3``. (default: ``default``)
        ids: A flag which determines whether ``id`` tags are included in the
            response. (default: ``false``)

    Returns:
        A JSON-formatted HTTP response with the possible statuses:
          * 200: OK
          * 500: Catchall processing error
    """
    namespaces = []
    param_ns = request.args.getlist('ns')
    if param_ns:
        for namespace in param_ns:
            namespaces.extend(namespace.split(','))

    include_ids = request.args.get('ids', 'false').lower() == 'true'

    try:
        return utils.http_json_response(
            await cmd.tags(
                namespaces,
                with_id_tags=include_ids,
            ),
        )
    except Exception:
        logger.exception('failed to get device tags')
        raise 
Example #27
Source File: test_plugin_signal_handlers.py    From sanicpluginsframework with MIT License 5 votes vote down vote up
def test_register_system_signals(spf):
    """Test if sanic register system signals"""
    app = spf._app
    plugin = TestPlugin()
    @plugin.route("/hello")
    async def hello_route(request):
        return HTTPResponse()

    plugin.listener("after_server_start")(stop)
    plugin.listener("before_server_start")(set_loop)
    plugin.listener("after_server_stop")(after)
    spf.register_plugin(plugin)
    app.run("127.0.0.1", 9999)
    assert calledq.get() is True 
Example #28
Source File: test_plugin_signal_handlers.py    From sanicpluginsframework with MIT License 5 votes vote down vote up
def test_dont_register_system_signals(spf):
    """Test if sanic don't register system signals"""
    app = spf._app
    plugin = TestPlugin()
    @plugin.route("/hello")
    async def hello_route(request):
        return HTTPResponse()

    plugin.listener("after_server_start")(stop)
    plugin.listener("before_server_start")(set_loop)
    plugin.listener("after_server_stop")(after)
    spf.register_plugin(plugin)
    app.run("127.0.0.1", 9999, register_sys_signals=False)
    assert calledq.get() is False 
Example #29
Source File: test_utils.py    From synse-server with GNU General Public License v3.0 5 votes vote down vote up
def test_http_json_response_from_list():
    actual = utils.http_json_response([1, 2, 3])

    assert isinstance(actual, HTTPResponse)
    assert actual.body == b'[1,2,3]'
    assert actual.status == 200
    assert actual.content_type == 'application/json' 
Example #30
Source File: handler.py    From sanic-transmute with MIT License 5 votes vote down vote up
def create_handler(transmute_func, context):

    @wraps(transmute_func.raw_func)
    async def handler(request, *args, **kwargs):
        exc, result = None, None
        try:
            args, kwargs = await extract_params(request, context,
                                                transmute_func)
            result = await transmute_func.raw_func(*args, **kwargs)
        except SanicException as se:
            code = se.status_code or 400
            exc = APIException(message=str(se), code=code)
        except Exception as e:
            exc = e
        content_type = request.headers.get("Content-Type", DEFAULT_HTTP_CONTENT_TYPE)
        response = transmute_func.process_result(
            context, result, exc, content_type
        )
        return HTTPResponse(
            status=response["code"],
            content_type=response["content-type"],
            headers=response["headers"],
            body_bytes=response["body"],
        )
    handler.transmute_func = transmute_func
    return handler