使用AWS Lambda+API网关构建restapi的轻量级框架
pylambdarest的Python项目详细描述
皮兰伯勒斯特
pylambdarest是一个轻量级的自定框架,用于使用AWS Lambda和{a6}构建restapi。在
动机
为什么是另一个框架?在
网关中的Lambda是一个由网关函数和Lambda代理函数共同触发的API。然后Lambda使用一个类似于Flask的框架来完成所有的路由。在API网关+Lambda上下文中,我觉得路由应该由API网关本身处理,然后将请求转发给每个资源或端点的特定Lambda函数。在
特点
- 没有路由。是的,这是一个特色。路由应该由API网关处理。在
- API网关事件解析(包括请求正文和路径参数)。在
- 更干净的语法。在
- 可选的主体架构和查询参数验证。在
安装
使用pip从PyPI安装包:
$ pip install pylambdarest
pylambdarest也应该包含在Lambda函数的部署包中。在
入门
pylambdarest提供了一个@route
修饰符,用于将API网关事件解析为一个Request
对象,该对象在handler函数中可用作参数。它还将处理程序的输出无缝地格式化为预期的Lambda+API网关格式。在
转动这个:
^{pr2}$在这方面:
frompylambdarestimportroute@route()defhandler(request):body=request.jsonquery_params=request.query_paramspath_params=request.path_paramsreturn200,{"message":f"Hello from AWS Lambda {body['name']}!!"}
您仍然可以从处理程序访问原始的event
和{
frompylambdarestimportroute@route()defhandler(request,event,context):print(event)body=request.jsonreturn200,{"message":f"Hello from AWS Lambda {body['name']}!!"}
API网关中定义的路径参数也可以作为函数参数直接访问:
frompylambdarestimportroute@route()defget_user(user_id):print(user_id)# get user from dbuser={"id":user_id,"name":"John Doe"}return200,user
架构验证
pylambdarest可选地使用jsonschema提供模式验证:
frompylambdarestimportrouteuser_schema={"type":"object","properties":{"name":{"type":"string"}},"required":["name"],"additionalProperties":False}@route(body_schema=user_schema)defcreate_user(request):# If the request's body does not# satisfy the user_schema,# a 400 will be returned# Create user herereturn201query_params_schema={"type":"object","properties":{# Only string types are allowed for query parameters.# Types casting should be done in the handler."page":{"type":"string"}},"additionalProperties":False}@route(query_params_schema=query_params_schema)defget_users(request):page=int(request.query_params.get("page",1))# request users in dbusers=[{"userId":i}foriinrange((page-1)*50,page*50)]return200,users
示例
您可以查看sample,以获得最小的pylambdarest API。在
在本例中,我们使用serverless框架来声明API网关->Lambda路由
Lambda函数的打包是使用serverless-python-requirements插件完成的。在
- 项目
标签: