带有可选json模式验证的azure函数的微框架
functionapprest的Python项目详细描述
功能测试
python路由mini framework for MS Azure Functions和可选的json模式验证。
**此存储库主要基于lambdarest project
功能
functionapp_handler
带有内置分派器的函数构造函数- decorator注册函数以处理http方法
- 使用相同的修饰符进行可选的json模式输入验证
安装
使用pip:
pip install functionapprest
开始
此模块帮助您在azure函数中处理不同的http方法。
fromfunctionapprestimportfunctionapp_handler@functionapp_handler.handle('get')defmy_own_get(event):return{'this':'will be json dumped'}
高级用法
也可以根据json模式验证传入的json主体:
my_schema={'$schema':'http://json-schema.org/draft-04/schema#','type':'object','properties':{'body':{'type':'object','properties':{'foo':{'type':'string'}}}}}@functionapp_handler.handle('get',path='/with-schema/',schema=my_schema)defmy_own_get(event):return{'this':'will be json dumped'}
查询参数
查询参数也用json模式进行分析和验证。 查询数组应以逗号分隔,所有数字都转换为浮点数。
my_schema={'$schema':'http://json-schema.org/draft-04/schema#','type':'object','properties':{'query':{'type':'object','properties':{'foo':{'type':'array','items':{'type':'number'}}}}}}@functionapp_handler.handle('get',path='/with-params/',schema=my_schema)defmy_own_get(event):returnevent.json['query']
路由
您还可以使用path
参数指定单个处理程序的反应路径:
@functionapp_handler.handle('get',path='/foo/bar/baz')defmy_own_get(event):return{'this':'will be json dumped'}
您还可以指定路径参数,这些参数将作为关键字参数传递:
@functionapp_handler.handle('get',path='/foo/<int:id>/')defmy_own_get(event,id):return{'my-id':id}
或者使用代理终结点:
@functionapp_handler.handle('get',path='/bar/<path:path>')defmy_own_get(event,path):return{'path':path}
在功能应用程序中使用
function.json
{"scriptFile":"handler.py","bindings":[{"authLevel":"anonymous","type":"httpTrigger","direction":"in","name":"req","methods":["get"],"route":"products/{product_id}"},{"type":"http","direction":"out","name":"$return"}]}
handler.py
fromfunctionapprestimportfunctionapp_handler,Request@functionapp_handler.handle('get',path='/products/<path:product_id>/')deflist_products(req:Request,product_id):query=req.json.get('query',{})body=req.json.get('body',{})headers=req.get('headers',{})params=req.get('params',{})response={'method':req.method,'url':req.url,'headers':headers,'params':params,'query':query,'body':body}returnresponsemain=functionapp_handler
测试
您可以使用pytest对当前的python版本运行测试。要运行当前python版本的测试,请运行pytest
有关测试依赖项,请参见^{pipenv install --dev
安装它们。
贡献者
爱德华多穆拉尔