前后端知识库 前后端知识库
首页
    • JavaScript
    • React
    • Vue
  • Python
  • Sanic
  • Linux
  • Ansible
归档
GitHub (opens new window)
首页
    • JavaScript
    • React
    • Vue
  • Python
  • Sanic
  • Linux
  • Ansible
归档
GitHub (opens new window)
  • Sanic

    • 开始
    • Routing
    • 请求数据
    • 响应
    • 静态资源
    • 异常
    • 中间件 和 监听器
    • 蓝图
    • WebSocket
    • 配置
    • Cookies
    • 处理装饰器
      • 认证装饰器
    • 流
    • 基于类的视图
    • 自定义协议
    • SSL 例子
    • 日志
    • 测试
    • 部署
    • 扩展
    • 贡献
    • API Reference
  • Python

  • backend
  • Sanic
devin
2023-09-07

处理装饰器

# 处理装饰器

由于 Sanic 处理程序是简单的 Python 函数,你可以用类似 Flask 的方法用装饰器包裹他们。一个经典的用例就是当你想要在处理程序的代码执行前先运行一些代码。

# 认证装饰器

假设你想要检查一个用户是否被授权去访问特定端点。你可以创建一个装饰器来包裹一个处理程序,检查一个请求是否客户端被授权去访问一个资源,并且发送一个合理的响应。

from functools import wraps
from sanic.response import json

def authorized():
    def decorator(f):
        @wraps(f)
        async def decorated_function(request, *args, **kwargs):
            # run some method that checks the request
            # for the client's authorization status
            is_authorized = check_request_for_authorization_status(request)

            if is_authorized:
                # the user is authorized.
                # run the handler method and return the response
                response = await f(request, *args, **kwargs)
                return response
            else:
                # the user is not authorized.
                return json({'status': 'not_authorized'}, 403)
        return decorated_function
    return decorator


@app.route("/")
@authorized()
async def test(request):
    return json({status: 'authorized'})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
编辑 (opens new window)
上次更新: 2023/09/07, 12:09:00
Cookies
流

← Cookies 流→

Theme by Vdoing | Copyright © 2023-2023 devin | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式