最好的烧瓶api库

flask-yoloapi的Python项目详细描述


烧瓶yoloapi

whoop

简单json端点的简单库。尤洛!

示例

获取

fromflask_yoloapiimportendpoint,parameter@app.route('/api/hello')@endpoint.api(parameter('name',type=str,required=True))defapi_hello(name):return"Hello %s!"%name

http://localhost:5000/api/hello?name=Sander

{data:"Hello Sander!"}

岗位

fromflask_yoloapiimportendpoint,parameter@app.route('/api/hello',methods=['POST'])@endpoint.api(parameter('name',type=str,required=True),parameter('age',type=int,default=18))defapi_hello(name,age):return"Hello %s, your age is %d"%(name,age)

curl -H "Content-Type: application/json" -vvXPOST -d '{"name":"Sander"}' http://localhost:5000/api/hello

{data:"Hello Sander, your age is 18"}

用例

  • 没有涉及类来生成api路由的样板代码。
  • 您不想从request.args/request.form/request.json:sleeping:
  • 您不需要将端点直接挂接到sqla模型。
  • 你不在乎提供rest遵从性——你只想要有点一致的json端点,该死!

安装

pip install flask-yoloapi

返回值

在上面的例子中,返回了一个字符串。还支持以下类型:

  • strunicodeintfloatdictlistdatetimeboolflask.Response
@app.route('/wishlist')@endpoint.api(parameter('category',type=str,required=False))defwishlist(category):ifcategory=="cars":return['volvo xc60','mclaren mp4-12c']
{"data":["volvo xc60","mclaren mp4-12c"]}

http状态代码

要返回不同的状态代码,请返回一个2长度的tuple,第二个索引是状态代码本身。

@app.route('/create_foo')@endpoint.api()defcreate_foo():return'created',201

路线参数

您仍然可以将Flask的路由参数与端点参数结合使用。

@app.route('/hello/<name>')@endpoint.api(parameter('age',type=int,required=True))defhello(name,age):return{'name':name,'age':age}

/hello/sander?age=27

{"data":{"age":27,"name":"sander"}}

默认值

可以通过default定义端点参数的默认值。

@app.route('/hello/<name>')@endpoint.api(parameter('age',type=int,required=False,default=10))defhello(name,age):return{'name':name,'age':age}

/hello/sander

{"data":{"age":10,"name":"sander"}}

键入批注

参数类型是必需的,但使用类型批注时除外。

python 3.5示例:

@app.route('/hello/',methods=['POST'])@endpoint.api(parameter('age',required=True),parameter('name',required=True))defhello(name:str,age:int):return{'name':name,'age':age}

相当于python 2:

@app.route('/hello/',methods=['POST'])@endpoint.api(parameter('age',type=int,required=True),parameter('name',type=str,required=True))defhello(name,age):return{'name':name,'age':age}

请注意,类型注释仅在Python3.5及更高版本(PEP484)中受支持。

自定义验证器

可以通过提供验证器函数来完成额外的参数验证。这个函数接受一个参数;输入。

defcustom_validator(value):ifvalue>120:raiseException("you can't possibly be that old!")@app.route('/hello/<name>')@endpoint.api(parameter('age',type=int,required=True,validator=custom_validator))defhello(name,age):return{'name':name,'age':age}

/hello/sander?age=130

{"data":"parameter 'age' error: you can't possibly be that old!"}

当验证不成功时,您可以执行两项操作:

  • 引发一个Exception,它将自动构造一个json响应。如上图所示。
  • 返回一个Flask.Response对象,您可以在其中构造自己的http响应

如果您需要更多关于传入类型的灵活性,请使用^ {CD22>}类型。

参数处理

此库在收集传入参数时相当投机,因为它将签入以下3个位置:

  • request.args
  • request.json
  • request.form

可以提供可选的location参数来指定参数的源。

@app.route('/login')@endpoint.api(parameter('username',type=str,location='form',required=True),parameter('password',type=str,location='form',required=True),)deflogin(username,password):return"Wrong password!",403

支持以下3个位置:

  • args-获取参数
  • form-通过http表单提交提交的参数
  • json-通过json编码的http请求提交的参数

日期时间格式

要以ISO 8601格式输出datetime对象(通过Date.parse()在javascript中解析这些对象很简单),请使用自定义json编码器。

fromdatetimeimportdatefromflask.jsonimportJSONEncoderclassApiJsonEncoder(JSONEncoder):defdefault(self,obj):ifisinstance(obj,(date,datetime)):returnobj.isoformat()returnsuper(ApiJsonEncoder,self).default(obj)app=Flask(__name__)app.json_encoder=ApiJsonEncoder

错误处理

当view函数本身引发异常时,将生成一个json响应,其中包括:

  • 错误消息
  • view函数的docstring
  • http 500

当不满足端点要求时,也会生成此错误响应。

{data:"argument 'password' is required",docstring:{help:"Logs the user in.",return:"The logged in message!",params:{username:{help:"The username of the user",required:true,type:"str"}},...

贡献者

  • 德罗默
  • Iksteen

测试

$ pytest --cov=flask_yoloapi tests
=========================================== test session starts ============================================
platform linux -- Python 3.5.3, pytest-3.1.3, py-1.5.2, pluggy-0.4.0
rootdir: /home/dsc/flask-yoloapi, inifile:
plugins: flask-0.10.0, cov-2.5.1
collected 19 items 

tests/test_app.py ...................

----------- coverage: platform linux, python 3.5.3-final-0 -----------
Name                          Stmts   Miss  Cover
-------------------------------------------------
flask_yoloapi/__init__.py         2      0   100%
flask_yoloapi/endpoint.py       111      4    96%
flask_yoloapi/exceptions.py       3      1    67%
flask_yoloapi/types.py            5      2    60%
flask_yoloapi/utils.py           52      5    90%
-------------------------------------------------
TOTAL                           173     12    93%

许可证

麻省理工学院。

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
试图读取字段“java”。lang.反对安卓。util。一对首先   gradle对java的影响。属性作为任务的输入?   java我的return语句不起作用。我做错了什么?   java通用同步代码块[无对象锁定]   macos Java小程序游戏不能在Mac上运行,即使它可以在PC上运行   java Firebase GeoFire设置位置未在服务中工作   java排序字符串对象   java通过JLabel上传背景图像(jpg)后,如何将图像缩放到它所在的面板上?   java无法连接到jsp中的数据库   java如何在整个ant taskdef操作的执行过程中拥有一个singleton类实例   java如何在按键事件中检查JTtextField中的字符串数字验证器   如何最好地输出大型单行XML文件(使用Java/Eclipse)?   内存不足,Java运行时环境无法在Java应用程序中继续运行   java Hibernate连接错误:组织上的NullPointerException。冬眠hql。阿斯特。HqlSqlWalker。createFromJoinElement   linux将参数从shell脚本传递到java类   java对于接受多个参数的setter是否有类似于@JsonCreator的注释?   java在链表中添加节点