本文整理汇总了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)
示例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)
示例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)
示例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)
示例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
示例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'}))
示例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)
示例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
示例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
示例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',
)
示例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(),
)
示例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
示例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
示例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
示例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