【问题标题】:Aiohttp with graphql: String cannot represent value带有graphql的Aiohttp:字符串不能代表值
【发布时间】:2021-03-07 08:58:42
【问题描述】:

我正在使用 graphql (aiohttp_graphql) 创建一个 aiohttp api,并给出了这个问题。为什么?

aiohttp 版本: aiohttp==3.7.3 -e git+https://github.com/graphql-python/aiohttp-graphql.git@5f7580310761dd7de33b44bc92f30b2695f2d523#egg=aiohttp_graphql

这是我的代码:

import asyncio
from aiohttp import web
from aiohttp_graphql import GraphQLView
from graphql.execution.executors.asyncio import AsyncioExecutor
from graphql import (graphql, GraphQLSchema, GraphQLObjectType, GraphQLField, GraphQLString)

async def resolve_hello(root, info):
    await asyncio.sleep(3)
    return 'World!'

Schema = GraphQLSchema(
    query=GraphQLObjectType(
        name='HelloQuery',
        fields={
            'hello': GraphQLField(
                GraphQLString,
                resolve=resolve_hello),
        },
    ))

app = web.Application()

GraphQLView.attach(
    app,
    route_path='/graphql',
    schema=Schema,
    graphiql=True,
    executor=AsyncioExecutor())

if __name__ == '__main__':
    web.run_app(app)

当我运行 GraphiQL 时

query {
  hello
}

GraphiQL 结果:

{
  "errors": [
    {
      "message": "String cannot represent value: <coroutine resolve_hello>",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "hello"
      ]
    }
  ],
  "data": {
    "hello": null
  }
}

终端返回: RuntimeWarning:从未等待协程“resolve_hello”

【问题讨论】:

    标签: python graphql aiohttp


    【解决方案1】:

    看起来像aiohttp_graphql got merged 变成graphql_server project

    所以安装后

    > pip install graphql-server[aiohttp] jinja2
    

    这个好像可以了

    import asyncio
    
    from aiohttp import web
    from graphql import (GraphQLField,
                         GraphQLObjectType,
                         GraphQLSchema,
                         GraphQLString)
    from graphql_server.aiohttp import GraphQLView
    
    
    async def resolve_hello(root, info):
        await asyncio.sleep(3)
        return 'World!'
    
    
    Schema = GraphQLSchema(
            query=GraphQLObjectType(
                    name='HelloQuery',
                    fields={
                        'hello': GraphQLField(
                                GraphQLString,
                                resolve=resolve_hello),
                    },
            ))
    
    app = web.Application()
    
    GraphQLView.attach(app,
                       route_path='/graphql',
                       schema=Schema,
                       graphiql=True,
                       # without this parameter coroutines as resolvers won't work
                       enable_async=True)
    
    if __name__ == '__main__':
        web.run_app(app)
    

    【讨论】:

      猜你喜欢
      • 2020-05-18
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 2019-03-28
      • 2021-02-05
      • 1970-01-01
      • 2013-10-24
      • 2020-06-03
      相关资源
      最近更新 更多