POST /users/login 方法提供username和password入参 username要求字符长序6-20之间 ,密码要求字符长度大于8
# main.py主文件添加路由
app.blueprint(Users,url_prefix='/users')
# users.py提供登录方法
from sanic.log import logger
from sanic_ext import validate
from app.entiies.account import Account
Users=Blueprint('users',url_prefix='/')
@Users.post('/login') # username (6-20) password (8-)
@validate(json=Account)
async def login(req:Request,body:Account)->HTTPResponse:
info=req.json
logger.info(info)
return json(info)
uv add sanic_ext # 加入扩展对应的是Account验证方法
pydantic验证 uv add pydantic
from pydantic import BaseModel,model_validator
from sanic.exceptions import SanicException
class Account(BaseModel):
username:str
password:str
@model_validator(mode='before')
def validators(cls,values):
username=values.get('username')
if len(username)<6 or len(username)>20:
raise SanicException('用户名长度6-20',status_code=400)
pwd=values.get('password')
if len(pwd)<8:
raise SanicException('密码长度小于8',status_code=400)
return values
业务集成标准化输出 {$code,$message}通过middleware实现
在主路由上实现中间件注册
app.register_middleware(middleware=logging,attach_to='response')
from sanic.request import Request
from sanic.response import HTTPResponse,json
from sanic.log import logger
from sanic import text,json
import json as json2
import uuid
async def logging(req:Request,res:HTTPResponse):
data=json2.loads(res.body.decode('utf-8'))
if data['status']==400:
return json({'code':f'10{data["status"]}','message':data['message'],'req-id':str(uuid.uuid4())},status=400)

1375

被折叠的 条评论
为什么被折叠?



