很棒的restapi。
layab的Python项目详细描述
Layab在索马里语中是Wonderful
的意思,也是Layabout
的快捷方式(难道我们都很懒吗)。在
这个包提供了可以用来帮助创建api的函数和类。在
如果您使用的是layab1.*(基于Flask-RestPlus,这个项目现在已经死了,从python3.9开始将不兼容),请参考Migration guide,因为layab现在提倡使用Starlette。在
为什么不从Flask-RestPlus切换到另一个基于Starlette的一体化框架(比如FastAPI或Responder)?在
Modularity is a key principle in software development. However the use of such framework prevent such development.
An all-in-one framework is more likely to requires hack to fit your usage.
An all-in-one framework is more likely to have a slower development and release pace.
By using layab 2, you can still use an all-in-one framework, but you also can chose what and if you want to:
Generate an OpenAPI definition.
Embed Swagger-UI.
Validate data.
Serialize / Deserialize data.
...
可用功能
Starlette
中间件
由于layab.starlette.middleware
函数,您可以获得一组已经创建的Starlette middleware。在
fromstarlette.applicationsimportStarlettefromlayab.starletteimportmiddlewareapp=Starlette(middleware=middleware())
默认情况下,您将拥有以下middleware:
- 日志中间件:接收和返回请求时记录请求(失败或成功)。在
- CORSMiddleware:允许跨源请求。在
- ProxyHeadersMiddleware:处理通过反向代理传递的请求。在
默认的responses可用于返回标准响应。在
位置响应
^{pr2}$配置
API和日志记录配置应该以YAML格式存储。在
配置应存储在configuration
文件夹中,该文件夹位于提供的文件路径的父文件夹中。在
API配置应该遵循“Configuration{env}.yml”命名,其中env是服务器环境变量的值。在
如果未找到,环境将被视为“默认”。在
日志配置使用相同的逻辑和以下名称加载:“Logging{env}.yml”。在
importlayab# Load logging and service configurationservice_configuration=layab.load('path/to/a/file/in/module/folder')
注意,如果日志配置文件包含Python代码的执行,则需要提供yaml.UnsafeLoader
加载程序。在
importlayabimportyaml# Load logging and service configurationservice_configuration=layab.load('path/to/a/file/in/module/folder',logging_loader=yaml.UnsafeLoader)
迁移指南
如果先前存在的信息丢失,请打开问题。在
创建应用程序和OpenAPI定义和Swagger UI端点
第1层*
importlayabapp,api=layab.create_api(__file__,compress_mimetypes=["text/csv","application/json"],title="My API.",description="My description.",)
Layab 2.*使用flask-restx
importflaskimportlayabfromlayab.flask_restximportenrich_flask,log_requests,Apiapp=flask.Flask(__name__)enrich_flask(app,compress_mimetypes=["text/csv","application/json"])api=Api(app,title="My API.",description="My description.",version="1.0.0",# You now have to set the version yourselfinfo={"x-server-environment":layab.get_environment()})log_requests(skip_paths=["/health"])
Layab 2.*使用Starlette
importlayabfromlayab.starletteimportmiddlewarefromstarlette.applicationsimportStarletteimportapispec_starletteapp=Starlette(middleware=middleware())spec=apispec_starlette.add_swagger_json_endpoint(app,title="My API.",version="1.0.0",# You now have to set the version yourselfinfo={"description":"My description.","x-server-environment":layab.get_environment(),})# You will however lose the Swagger-ui that was available on / (root endpoint)# We advise to install it on your Docker image first and then serve the directory as "/" as the last declared route.
监测终点
第1层*
importlayabapi=Nonedefhealth_details():pass# Implement thislayab.add_monitoring_namespace(api,health_details)
Layab 2.*使用flask-restx
importos.pathfromhealthpy.flask_restximportadd_consul_health_endpointfromkeepachangelog.flask_restximportadd_changelog_endpointapi=Noneasyncdefhealth_check():pass# Implement thisnamespace=api.namespace("Monitoring",path="/",description="Monitoring operations")# You now have to set the release_id yourselfadd_consul_health_endpoint(namespace,health_check,release_id="1.0.0")# You now have to set the path to the changelog yourselfchangelog_path=os.path.join(os.path.abspath(os.path.dirname(__file__)),"..","CHANGELOG.md")add_changelog_endpoint(namespace,changelog_path)
Layab 2.*使用Starlette
importos.pathfromstarlette.applicationsimportStarlettefromhealthpy.starletteimportadd_consul_health_endpointfromkeepachangelog.starletteimportadd_changelog_endpointapp=Starlette()asyncdefhealth_check():pass# Implement thisadd_consul_health_endpoint(app,health_check)# You now have to set the path to the changelog yourselfchangelog_path=os.path.join(os.path.abspath(os.path.dirname(__file__)),"..","CHANGELOG.md")add_changelog_endpoint(app,changelog_path)
现在您只能添加最初提供的两个端点中的一个(以防您没有或不想公开更改)。在
请参阅healthpy文档以了解有关检查API运行状况的更多信息。在
有关如何处理changelog的详细信息,请参阅keepachangelog文档。在
创建响应
第1层*
importlayabapi=None@api.doc(**layab.created_response_doc(api))defendpoint():returnlayab.created_response("/this_is_the_location")
Layab 2.*使用flask-restx
importflask_restxfromlayab.flask_restximportlocation_responseapi=None@api.response(201,"Resource created",flask_restx.fields.String,headers={"location":"Resource location."})defendpoint():returnlocation_response("/this_is_the_location")
Layab 2.*使用Starlette
fromlayab.starletteimportLocationResponsedefendpoint(request):""" responses: 201: description: "Resource created" headers: location: description: "Resource location." type: string schema: type: string """returnLocationResponse(request,"/this_is_the_location")
更新响应
第1层*
importlayabapi=None@api.doc(**layab.updated_response_doc(api))defendpoint():returnlayab.updated_response("/this_is_the_location")
Layab 2.*使用flask-restx
importflask_restxfromlayab.flask_restximportlocation_responseapi=None@api.response(201,"Resource updated",flask_restx.fields.String,headers={"location":"Resource location."})defendpoint():returnlocation_response("/this_is_the_location")
Layab 2.*使用Starlette
fromlayab.starletteimportLocationResponsedefendpoint(request):""" responses: 201: description: "Resource updated" headers: location: description: "Resource location." type: string schema: type: string """returnLocationResponse(request,"/this_is_the_location")
删除响应
第1层*
importlayabapi=None@api.response(*layab.deleted_response_doc)defendpoint():returnlayab.deleted_response
Layab 2.*使用flask-restx
importflaskapi=None@api.response(204,"Resource deleted")defendpoint():returnflask.Response(b"",status=204)
Layab 2.*使用Starlette
fromstarlette.responsesimportResponsedefendpoint(request):""" responses: 204: description: "Resource deleted" """returnResponse(status_code=204)
如何安装
- python 3.6+必须安装
- 要使用pip安装的模块:
python -m pip install layab
- 项目
标签: