Django视图中的GraphQL集成
Django视图中的GraphQL集成,需要使用django-graphene库。以下是详细步骤:
- 安装django-graphene库:
pip install graphene-django
- 在Django的settings.py文件中添加以下配置:
INSTALLED_APPS = [
# ...
'graphene_django',
]
GRAPHENE = {
'SCHEMA': 'myproject.schema.schema', #指定GraphQL模式的位置
}
- 创建一个GraphQL模式的schema.py文件:
import graphene class Query(graphene.ObjectType): hello = graphene.String(argument=graphene.String(default_value="pidancode.com")) def resolve_hello(self, info, argument): return f'Hello {argument}!' schema = graphene.Schema(query=Query)
- 在视图中将GraphQL模式绑定到URL:
from django.http import JsonResponse from graphene_django.views import GraphQLView urlpatterns = [ # ... path('graphql', GraphQLView.as_view(graphiql=True)), ]
在访问/example/时,将会看到GraphQL的操作界面。
- 在GraphQL查询中使用字符串作为范例:
{
hello(argument: "皮蛋编程")
}
将会得到以下响应:
{
"data": {
"hello": "Hello 皮蛋编程!"
}
}
相关文章