草莓法斯塔皮返回错误"'dict' object has no attribute 'name'"



我正试图从Rick&Morty将graphql与Fastapi+StrawBerry一起使用,我在写的第一个字段总是会出现同样的错误

我的代码:

from fastapi import FastAPI
import strawberry
from strawberry.fastapi import GraphQLRouter
import requests
@strawberry.type
class Character:
id: int
name: str
status: str
species: str
@strawberry.type
class Query:
@strawberry.field
def getIdent(self, ch: str) -> Character:
url = f'https://rickandmortyapi.com/api/character/{ch}'
return requests.get(url).json()
app = FastAPI()
schema = strawberry.Schema(Query)
graphql_app = GraphQLRouter(schema)
app.include_router(graphql_app, prefix="/graphql")

我的graphql查询:

query MyQuery {
getIdent(ch: "2") {
name
species
}
}

错误:

{
"data": null,
"errors": [
{
"message": "'dict' object has no attribute 'name'",
"locations": [
{
"line": 3,
"column": 5
}
],
"path": [
"getIdent",
"name"
]
}
]
}

Strawberry默认情况下不允许返回字典,这样做是为了确保代码的类型安全,但有一个配置选项允许您这样做。使用StrawberryConfig和自定义默认解析器,您可以允许返回字典和实例,请参见以下示例:

https://play.strawberry.rocks/?gist=c788907c4421b55d3cb077431fe3b6c7

此处的相关代码:

# a custom default resolver that tries to use getitem 
# to get the return value, otherwise it fallbacks to 
# the default behaviour, which is getattr
def default_resolver(root, field):
try:
return operator.getitem(root, field)
except KeyError:
return getattr(root, field)
config = StrawberryConfig(
default_resolver=default_resolver
)
schema = strawberry.Schema(query=Query, config=config)

相关内容

最新更新