Django中的GraphQL查询未返回 [英] GraphQL queries in Django returning None

查看:79
本文介绍了Django中的GraphQL查询未返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Django中使用graphQL查询.基本上,我有两个应用程序,一个是"api"应用程序,其中包含执行查询所需的一切,另一个是"frontend",我从中调用该API来使用这些查询.

我可以使用GraphQL视图在其中键入查询,并且可以完美地工作,但是每当我尝试进行查询时,我都会得到:"OrderedDict([[''users',None)])"

在GraphQl视图中查询的结果

代码:

在"api"中,我的 schema.py :

 导入石墨烯导入graphql_jwt从石墨烯导入中继,ObjectType,AbstractType,列表,字符串,Field,InputObjectType从graphene_django导入DjangoObjectType从graphene_django.filter导入DjangoFilterConnectionField从datetime导入日期开始,datetime从django.contrib.auth.models导入用户从django.contrib.auth导入get_user_model....Query(graphene.ObjectType)类:我= graphene.Field(UserType)用户= graphene.List(UserType)配置文件= relay.Node.Field(ProfileNode)all_profiles = DjangoFilterConnectionField(ProfileNode)def resolve_users(自身,信息):###返回所有用户###用户= info.context.user如果user.is_anonymous:引发异常('未记录!')如果不是user.is_superuser:引发异常(拒绝拒绝")返回User.objects.all()def resolve_me(自我,信息):###返回登录的用户###用户= info.context.user如果user.is_anonymous:引发异常('未记录!')回头用户def resolve_all_profiles(self,info,** kwargs):###返回所有配置文件###返回Profile.objects.all().....def execute(my_query):schema = graphene.Schema(查询=查询)返回schema.execute(my_query) 

以及在我的应用前端中调用应用"api"的 views.py :

来自django.shortcuts的

 导入渲染进口石墨烯从api导入架构从django.contrib.auth导入身份验证def accueil(要求):如果request.user.is_authenticated:检查=我已登录";别的:检查=我没有登录"结果= schema.execute(")查询{用户{ID用户名}}"返回render(request,'frontend/accueil.html',{'result':result.data,'check':check}) 

模板:

 < h1> OTC</h1>< p>用户是:{{result}}</p>< br/>< p> {{check}}</p>< a href =" {%url'login'%}'> login</a>< a href =" {%url'logout'%}'> logout</a> 

最后:

网页结果

以及控制台中的错误:

 解析字段Query.users时发生错误追溯(最近一次通话):在resolve_or_error的第311行中,文件"/home/victor/myenv/lib/python3.5/site-packages/graphql/execution/executor.py"返回executor.execute(resolve_fn,source,info,** args)执行中的文件"/home/victor/myenv/lib/python3.5/site-packages/graphql/execution/executors/sync.py",第7行返回fn(* args,** kwargs)在resolve_users中的文件"/home/victor/poc2/poc2/api/schema.py",第67行用户= info.context.userAttributeError:'NoneType'对象没有属性'user'追溯(最近一次通话):在complete_value_catching_error中的第330行中,文件"/home/victor/myenv/lib/python3.5/site-packages/graphql/execution/executor.py"exe_context,return_type,field_asts,信息,结果)在complete_value中的文件"/home/victor/myenv/lib/python3.5/site-packages/graphql/execution/executor.py",第383行引发GraphQLLocatedError(field_asts,original_error = result)graphql.error.located_error.GraphQLLocatedError:'NoneType'对象没有属性'user' 

解决方案

除非您正在编写测试客户端,否则您可能正在从中调用 schema.execute 在Django视图中.但是假设您有这样做的理由,那么您的特定问题是,在 accueil 视图中调用 schema.execute 时,您没有通过用户.

看看执行文档,您将看到需要为上下文提供一个可选参数.您的代码未提供上下文,因此,根据您的例外情况, info.context None .不幸的是,这个例子

  result = schema.execute('{name}',context_value = {'name':'Syrus'}) 

不是特定于Django的.但是我认为在Django功能视图中有效的是:

  result = schema.execute(查询,context_value =请求) 

I am trying to use graphQL queries in django. Basically I have two apps, my 'api' app which contains everything I need to make the queries and another one called 'frontend' from which I call the api to use these queries.

I can use the GraphQL view to type queries in it and it works perfectly, but whenever I try to make the query, I get this: "OrderedDict([('users', None)])"

Result of my query in the GraphQl view

The code:

In 'api' my schema.py:

import graphene
import graphql_jwt
from graphene import relay, ObjectType, AbstractType, List, String, Field,InputObjectType
from graphene_django import DjangoObjectType
from graphene_django.filter import DjangoFilterConnectionField
from datetime import date, datetime
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model

....

class Query(graphene.ObjectType):
    me = graphene.Field(UserType)
    users = graphene.List(UserType)
    profile = relay.Node.Field(ProfileNode)
    all_profiles = DjangoFilterConnectionField(ProfileNode)

    def resolve_users(self, info):
        ### Returns all users ###
        user = info.context.user
        if user.is_anonymous:
            raise Exception('Not logged!')
        if not user.is_superuser:
            raise Exception('premission denied')
        return User.objects.all()

    def resolve_me(self, info):
        ### Returns logged user ###
        user = info.context.user
        if user.is_anonymous:
            raise Exception('Not logged!')
        return user

    def resolve_all_profiles(self, info, **kwargs):
        ### Returns all profiles ###
        return Profile.objects.all()

.....

def execute(my_query):
    schema = graphene.Schema(query=Query)
    return schema.execute(my_query)

And the views.py that calls the app 'api' in my app frontend:

from django.shortcuts import render
import graphene
from api import schema
from django.contrib.auth import authenticate


def accueil(request):

    if request.user.is_authenticated:
        check = "I am logged"
    else:
        check = "I am not logged"

    result = schema.execute("""query {
                                users {
                                    id
                                    username
                                }
                            }""")

    return render(request, 'frontend/accueil.html', {'result' : result.data, 'check' : check})

The template :

<h1>OTC</h1>
<p> the users are : {{result}}</p>
<br/>
<p>{{check}}</p>
<a href="{%url 'login'  %}">login</a>
<a href="{%url 'logout' %}">logout</a>

and finally:

The web page result

and the error in the console:

An error occurred while resolving field Query.users
Traceback (most recent call last):
  File "/home/victor/myenv/lib/python3.5/site-packages/graphql/execution/executor.py", line 311, in resolve_or_error
    return executor.execute(resolve_fn, source, info, **args)
  File "/home/victor/myenv/lib/python3.5/site-packages/graphql/execution/executors/sync.py", line 7, in execute
    return fn(*args, **kwargs)
  File "/home/victor/poc2/poc2/api/schema.py", line 67, in resolve_users
    user = info.context.user
AttributeError: 'NoneType' object has no attribute 'user'
Traceback (most recent call last):
  File "/home/victor/myenv/lib/python3.5/site-packages/graphql/execution/executor.py", line 330, in complete_value_catching_error
    exe_context, return_type, field_asts, info, result)
  File "/home/victor/myenv/lib/python3.5/site-packages/graphql/execution/executor.py", line 383, in complete_value
    raise GraphQLLocatedError(field_asts, original_error=result)
graphql.error.located_error.GraphQLLocatedError: 'NoneType' object has no attribute 'user'

解决方案

Unless you're writing a test client, you probably should not be calling schema.execute from inside a Django view. But assuming that you have your reasons for doing this, your specific problem is that you're not passing the user when you invoke schema.execute in accueil view.

Have a look at the execute documentation and you'll see that you'll need to supply an optional argument for the context. Your code is not supplying a context, hence the info.context is None, as per your exception. Unfortunately, the example

result = schema.execute('{ name }', context_value={'name': 'Syrus'})

is not Django-specific. But I think what works in a Django functional view is:

result = schema.execute(query, context_value=request)

这篇关于Django中的GraphQL查询未返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆