StarletteWeb框架的自定义json序列化程序。
starlette-json的Python项目详细描述
Starlette Json
简介
针对python社区中可用的各种json序列化程序的Starlette json响应。在
为什么:
- 从核心starlette包中删除
ujson
依赖项 - 为其他序列化程序添加适配器
- 自定义序列化程序呈现设置
要求
- Python 3.6+
- Starlette
安装
$ pip install starlette-json
可选安装
至少安装其中一个:
- orjson
pip install orjson
- Ultrajson
pip install ujson
- Rapidjson
pip install python-rapidjson
- SimpleJson
pip install simplejson
使用
响应示例
^{pr2}$自定义响应呈现选项:
有关可用选项,请参阅特定json序列化程序的文档
fromstarlette.applicationsimportStarlettefromstarlette_jsonimportORJsonResponse,UJsonResponse,RapidJsonResponseimportorjsonapp=Starlette()data={'Hello':'World'}@app.route('/orjson')deforjson(request):returnORJsonResponse(data,default=lambdax:str(x),option=orjson.OPT_STRICT_INTEGER|orjson.OPT_NAIVE_UTC)@app.route('/ujson')defujson(request):returnUJsonResponse(data,encode_html_chars=True,ensure_ascii=False,escape_forward_slashes=False)@app.route('/rapidjson')defrapidjson(request):returnRapidJsonResponse(data,sort_keys=True,indent=4)@app.route('/simplejson')defrapidjson(request):returnSimpleJsonResponse(data,skipkeys=False,ensure_ascii=True,check_circular=True,allow_nan=True)
Json请求正文解析:
fromstarlette.applicationsimportStarlettefromstarlette_jsonimportORJsonMiddleware,ORJsonResponseapp=Starlette()app.add_middleware(ORJsonMiddleware)@app.route('/orjson')deforjson(request):body=awaitrequest.json()# Parsed with orjsonreturnORJsonResponse({'message':'ok'})
贡献
非常欢迎。 CONTRIBUTING.md
待办事项
- 测试?在
- 项目
标签: