zoukankan      html  css  js  c++  java
  • sanic中间件和监听器

    一:中间件

    中间件是服务器在请求之前或之后执行的功能,他们可以用来修改修改用户定义处理函数的请求或相应。

    Sanic提供两种类型的中间件:请求和响应。

    两者都是使用@app.middleware装饰器声明,两个装饰器分别需要传入一个代表其类型的参数:requestresponse

    下面举一个简单的栗子:

    from sanic.response import text
    @app.route("/get_info")
    async def get_info(request):
      print(request.url)
      return text("it is ok!")
    @app.middleware("request")
    async def get_request_middleware(request):
      print("请求中间件")
    @app.middleware("response")
    async def get_response_middleware(request,response):
      print("响应中间件")

    当我们访问/get_info请求时,打印结果将会是这样的:

    请求中间件
    
    http://localhost:5000/get_info
    
    响应中间件

    二:监听器

    如果需要在服务器启动/关闭的时候,执行一些特殊的代码,则可以使用以下监听器:

    before_server_start:在服务器启动之前执行

    after_server_start:在服务器启动之后执行

    before_server_stop:在服务器关闭之前执行

    after_server_stop:在服务器关闭之后执行

    举个栗子:

    @app.listener("before_server_start")
    async def before_server_start(request,loop):
      print("before_server_start")
    @app.listener("after_server_start")
    async def after_server_start(request,loop):
      print("after_server_start")
    @app.listener("before_server_stop")
    async def before_server_stop(request,loop):
      print("before_server_stop")
    @app.listener("after_server_stop")
    async def after_server_stop(request,loop):
      print("after_server_stop")
  • 相关阅读:
    Python中 sys.argv[]的用法简明解释
    python多线程
    python 多进程
    shell----bash
    linux crontab
    Elastic search 概述
    Elastic search 入门
    Elastic search CURL命令
    Elastic search 基本使用
    Elastic search 字段折叠 collaose
  • 原文地址:https://www.cnblogs.com/zzy-9318/p/10104948.html
Copyright © 2011-2022 走看看