zoukankan      html  css  js  c++  java
  • 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)
    
  • 相关阅读:
    hdu1556 Color the ball
    HDU
    《解读window核心编程》 之 字符和字符串处理方式
    WebService之CXF注解之四(測试类)
    gdal以GA_Update方式打开jpg文件的做法
    贪吃蛇源代码分析
    极光消息推送服务器端开发实现推送(上)
    2014,为了梦想宁愿破釜沉舟
    小强的HTML5移动开发之路(37)——jqMobi快速入门
    你可能不知道的5种 CSS 和 JS 的交互方式
  • 原文地址:https://www.cnblogs.com/fhkankan/p/14763607.html
Copyright © 2011-2022 走看看