graphene django
v3.2.2
Graphene-Django 是一个开源库,可在 Django(高级 Python Web 框架)和 Graphene(用于构建 GraphQL API 的库)之间提供无缝集成。该库允许开发人员在 Django 中快速高效地创建 GraphQL API,同时保持高水平的性能。
要安装 Graphene-Django,请运行以下命令:
pip install graphene-django
安装后,将“graphene_django”添加到 Django 项目的INSTALLED_APPS
列表中,并在项目设置中定义 GraphQL 架构:
INSTALLED_APPS = [
# ...
'graphene_django' ,
]
GRAPHENE = {
'SCHEMA' : 'myapp.schema.schema'
}
要使用 Graphene-Django,请在 Django 应用程序目录中创建schema.py
文件并定义 GraphQL 类型和查询:
import graphene
from graphene_django import DjangoObjectType
from . models import MyModel
class MyModelType ( DjangoObjectType ):
class Meta :
model = MyModel
class Query ( graphene . ObjectType ):
mymodels = graphene . List ( MyModelType )
def resolve_mymodels ( self , info , ** kwargs ):
return MyModel . objects . all ()
schema = graphene . Schema ( query = Query )
然后,在 Django 项目的urls.py
文件中公开 GraphQL API:
from django . urls import path
from graphene_django . views import GraphQLView
from . import schema
urlpatterns = [
# ...
path ( 'graphql/' , GraphQLView . as_view ( graphiql = True )), # Given that schema path is defined in GRAPHENE['SCHEMA'] in your settings.py
]
Graphene-Django 支持使用 Django 的测试客户端测试 GraphQL API。要创建测试,请在 Django 应用程序目录中创建一个tests.py
文件并编写测试用例:
from django . test import TestCase
from graphene_django . utils . testing import GraphQLTestCase
from . import schema
class MyModelAPITestCase ( GraphQLTestCase ):
GRAPHENE_SCHEMA = schema . schema
def test_query_all_mymodels ( self ):
response = self . query (
'''
query {
mymodels {
id
name
}
}
'''
)
self . assertResponseNoErrors ( response )
self . assertEqual ( len ( response . data [ 'mymodels' ]), MyModel . objects . count ())
随时欢迎为 Graphene-Django 做出贡献!首先,请检查存储库的问题跟踪器和贡献指南。
Graphene-Django 在 MIT 许可证下发布。
如果您遇到任何问题或对 Graphene-Django 有疑问,请随时在官方 GitHub 存储库上提交问题。您还可以在 Discord 上的 Graphene-Django 社区寻求帮助并分享您的经验