asyncio+graphql=快速简单的api
aiographql的Python项目详细描述
- asyncio-显式并发to reduce race conditions
- graphql-你只需要一个请求+你的api的自动文档就可以了
- uvloop, protocol-top performance
- 最小的http-与rest框架不同,rest框架浪费时间在/graphqlendpoint上
- 可插入上下文-用于身份验证、日志记录等
- 异常处理-在所有级别,使用默认或自定义处理程序
用法:
pip install aiographql cat <<'END' >serve.py import asyncio, aiographql, graphene class User(graphene.ObjectType): id = graphene.ID(required=True) name = graphene.String() class Query(graphene.ObjectType): me = graphene.Field(User) async def resolve_me(self, info): await asyncio.sleep(1) # DB return User(id=42, name='John') schema = graphene.Schema(query=Query, mutation=None) aiographql.serve(schema, listen=[ dict(protocol='tcp', port=25100), dict(protocol='unix', path='/tmp/worker0'), ]) END python3 serve.py curl http://localhost:25100/ --data-binary \ '{"query": "{ me { id name } }", "variables": null}' # OR: curl --unix-socket /tmp/worker0 http:/ --data-binary ... # Result: # 1 second async await for DB and then: {"data":{"me":{"id":"42","name":"John"}}}
请参阅more examples and tests关于jwt身份验证、并发慢速数据库查询等。
config:
import aiographql; help(aiographql.serve) serve(schema, listen, get_context=None, exception_handler=None, enable_uvloop=True, run=True) Configure the stack and start serving requests
schema:graphene.Schema-要服务的GraphQL模式
listen:list-要侦听连接的一个或多个终结点:
- ^{tt6}$ - create_server() docs
- ^{tt7}$ - create_unix_server() docs
get_context:None或[async] callable(loop, context: dict): mixed-从与exception_handler()统一的输入生成类似于图形的上下文身份验证
exception_handler:None或callable(loop, context: dict)-在the docs+
中定义的默认或自定义异常处理程序- ^{tt15}$: ^{tt16}$ or ^{tt9}$ - HTTP headers, if known
- ^{tt18}$: ^{tt19}$ or ^{tt16}$ or ^{tt9}$ - accumulated HTTP request before content length is known, then accumulated content, then GraphQL request
enable_uvloop:bool-启用uvloop以获得最佳性能,除非有更好的循环
run:bool-如果True,则运行循环;False对于测试很好
返回servers:Servers-await servers.close()以关闭侦听套接字-适合测试