GraphQL的现代Python实现。
项目描述
Pygraphy
一个现代Python风格的GraphQL实现,为Python开发者提供无痛苦的开发体验。
文档
见官方文档。
快速预览
Pygraphy的所有行为都与您的直觉一致。
import asyncio
import pygraphy
from typing import List, Optional
from starlette.applications import Starlette
import uvicorn
app = Starlette(debug=True)
class Episode(pygraphy.Enum):
NEWHOPE = 4
EMPIRE = 5
JEDI = 6
class Character(pygraphy.Interface):
"""
Character interface contains human and droid
"""
id: str
name: str
appears_in: List[Episode]
@pygraphy.field
def friends(self) -> Optional[List['Character']]:
return []
class Human(pygraphy.Object, Character):
"""
Human object
"""
home_planet: str
class Droid(pygraphy.Object, Character):
"""
Driod object
"""
primary_function: str
class Query(pygraphy.Query):
@pygraphy.field
async def hero(self, episode: Episode) -> Optional[Character]:
await asyncio.sleep(1)
return Droid(
id="2001",
name="R2-D2",
appears_in=[Episode.NEWHOPE, Episode.EMPIRE, Episode.JEDI],
primary_function="Astromech",
)
@app.route('/')
class Schema(pygraphy.Schema):
query: Optional[Query]
if __name__ == '__main__':
uvicorn.run(app, host='0.0.0.0', port=8000)
安装
需要Web服务器
pip install 'pygraphy[web]'
独立模型和查询处理器
pip install 'pygraphy'
特性
- 干净的Python模式定义系统
- 模型定义基于Python Dataclass
- 支持Python Asyncio
- 基于Python Context Variables的上下文管理
- 支持查询和GraphQL Playground
与GraphQL-Core(-Next)的比较
优势
GraphQL-Core-Next是GraphQL的官方支持实现,它只是一个基本库。通常,您应该使用Graphene或其他基于它的包装库。Pygraphy是一个集成库,包括数据映射和模型定义。
GraphQL-Core-Next直接从GraphQL.js翻译而来,这导致了一些奇怪的行为,例如graphql-core-next/issues/37,并且很难为其编写包装器。Pygraphy以一种更Python化的方式重写了模式定义系统。通过使用Python元类,Pygraphy可以自然地支持类风格的模式定义。Lambda函数解析器(丑陋的Js风格)和实例方法解析器之间不再有冲突。
通过使用Python 3.7版本中添加的上下文变量,Pygraphy无需像graphql-core-next那样在调用链中传递上下文。
此外,Pygraphy比graphql-core-next更快,您可以查看以下基准测试结果。
更重要的是,Pygraphy明确支持使用Python异步生成器的有状态订阅方法,这在graphql-core-next中并没有详细说明。
缺点
Pygraphy目前仍处于预alpha版本,需要稳定,欢迎反馈。
目前Pygraphy不支持根据规范中的全部GraphQL功能,规范中的其余部分将在未来直接集成,包括
- 指令
- ID标量
- 类型扩展
- 一些验证检查
大多数功能已经实现,所以请不要担心。
基准
与Strawberry / graphql-core-next相比,Pygraphy的速度是其4.5倍。
↳ uname -a
Darwin Workstation.local 19.0.0 Darwin Kernel Version 19.0.0: Thu Jul 11 18:37:36 PDT 2019; root:xnu-6153.0.59.141.4~1/RELEASE_X86_64 x86_64
↳ python -V
Python 3.7.2
↳ time python benchmark/test_pygraphy.py
python benchmark/test_pygraphy.py 3.48s user 0.10s system 99% cpu 3.596 total
↳ time python benchmark/test_strawberry.py
python benchmark/test_strawberry.py 16.05s user 0.16s system 99% cpu 16.257 total
项目详情
下载文件
下载适用于您平台文件的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。
源代码分发
构建分发
pygraphy-0.2.5-py3-none-any.whl的散列
算法 | 散列摘要 | |
---|---|---|
SHA256 | 4588fcec719381d718ec4462289f8a15ee5fd9e6acb0759d0a82f91bea5f71ed |
|
MD5 | 15329e66f27ae6f453d8d7aa71525828 |
|
BLAKE2b-256 | 1aef9a224743c1ecdf9a4e83df6792d61b5687cbeb99b02c829fb6d6fb635cd3 |