使用类型注释解析sanic中的查询参数
sanicargs的Python项目详细描述
Sanicargs
分析Sanic中的查询参数 使用类型批注。
调查
请填写this survey 如果您使用的是Sanicargs,我们将收集反馈:-)
安装
使用pip安装
$ pip install sanicargs
使用量
使用parse_query_argsdecorator解析查询参数和类型转换 使用查询参数和路径参数 Sanic的路线或蓝图 就像在 example 下面:
importdatetimefromsanicimportSanic,responsefromsanicargsimportparse_query_argsapp=Sanic("test_sanic_app")@app.route("/me/<id>/birthdate",methods=['GET'])@parse_query_argsasyncdeftest_datetime(req,id:str,birthdate:datetime.datetime):returnresponse.json({'id':id,'birthdate':birthdate.isoformat()})if__name__=="__main__":app.run(host="0.0.0.0",port=8080,access_log=False,debug=False)
使用
$ curl 'http://0.0.0.0:8080/me/123/birthdate?birthdate=2017-10-30'
字段
- str:ex: ?message=hello world
- int:ex: ?age=100
- bool:ex: ?missing=false
- datetime.datetime: ex: ?currentdate=2017-10-30T10:10:30 or 2017-10-30
- datetime.date:ex: ?birthdate=2017-10-30
- list[str]:ex: ?words=you,me,them,we
注意日期时间
对日期和日期时间进行分析时,没有时区信息为您提供 “原始日期时间”对象。请参阅上的注释 datetime.timestamp() 关于处理时区,如果您需要epoch格式的时间戳。
关于装饰工的重要注意事项
像往常一样,decorators序列在python中很重要。
您需要应用parse_query_argsdecorator作为第一个 执行,这意味着最接近def。
request是必需的!
您应该始终将request作为函数中的第一个参数 使用parse_query_args的顺序。
注意requestarg可以重命名,甚至可以将类型注释为 只要是第一个参数。
历史记录
0.0.1(2017-01-09)
- Git初始化
1.0.0(2017-01-12)
- 添加了测试套件
- 添加了路径参数类型转换
1.1.0(2018-03-01)
- 请求可以重命名,甚至可以键入注释
1.2.0(2018-03-01)
- 增加了对布尔参数的支持
1.3.0(2019-01-08)
- @包装内部函数以保留args签名
1.4.0(2019-03-04)
- 更新deps以允许sanic的最新版本