Django中的GraphQL查询返回None

时间:2018-04-19 10:37:23

标签: python django graphql graphene-python

大家好,

所以我试图在django中使用graphQL查询。基本上我有两个应用程序,我的'api'应用程序包含我需要进行查询的所有内容,另一个叫做'frontend',我称之为api来使用这些查询。

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

Result of my query in the GraphQl view

代码:

在'api'我的 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)

在我的应用前端调用应用'api'的 views.py

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})

模板:

<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>

最后:

The web page result

和控制台中的错误:

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'

任何帮助都是受欢迎的家伙,我只是无法弄清楚为什么它不起作用,因为我已经登录并且一切都在graphql视图中完美运行

ps:对不起,如果我犯了一些错误,英语不是我的母语

1 个答案:

答案 0 :(得分:3)

除非您正在编写测试客户端,否则您可能从Django视图中调用schema.execute。但假设您有理由这样做,您的具体问题是,当您在schema.execute视图中调用accueil时,您并未传递用户。

查看execute documentation,您会发现您需要为上下文提供可选参数。您的代码未提供上下文,因此info.contextNone,根据您的例外情况而定。不幸的是,这个例子

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

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

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