Sanic官翻-自定义通讯协议

自定义通讯协议

注意

这是高级用法,大多数读者将不需要这种功能。

您可以通过指定自定义协议来更改Sanic协议的行为,该协议应该是asyncio.protocol的子类。然后可以将该协议作为关键字参数protocol传递给sanic.run方法。

定制协议类的构造函数从Sanic接收以下关键字参数。

  • loop:异步兼容的事件循环。
  • connections:存储协议对象的集合。当Sanic收到SIGINT或SIGTERM时,它将对存储在此集中的所有协议对象执行protocol.close_if_idle
  • signal:具有停止属性的sanic.server.Signal对象。当Sanic收到SIGINT或SIGTERM时,signal.stopped分配为True。
  • request_handler:以sanic.request.Request对象和响应回调作为参数的协程。
  • error_handlersanic.exceptions.Handler,在引发异常时调用。
  • request_timeout:请求超时之前的秒数。
  • request_max_size:整数,以字节为单位指定请求的最大大小。

示例

如果处理程序函数未返回HTTPResponse对象,则默认协议中将发生错误。

通过重写write_response协议方法,如果处理程序返回字符串,它将被转换为HTTPResponse对象。

from sanic import Sanic
from sanic.server import HttpProtocol
from sanic.response import text

app = Sanic(__name__)


class CustomHttpProtocol(HttpProtocol):

    def __init__(self, *, loop, request_handler, error_handler,
                 signal, connections, request_timeout, request_max_size):
        super().__init__(
            loop=loop, request_handler=request_handler,
            error_handler=error_handler, signal=signal,
            connections=connections, request_timeout=request_timeout,
            request_max_size=request_max_size)

    def write_response(self, response):
        if isinstance(response, str):
            response = text(response)
        self.transport.write(
            response.output(self.request.version)
        )
        self.transport.close()


@app.route('/')
async def string(request):
    return 'string'


@app.route('/1')
async def response(request):
    return text('response')

app.run(host='0.0.0.0', port=8000, protocol=CustomHttpProtocol)
原文地址:https://www.cnblogs.com/fhkankan/p/14763607.html