我一直在玩graphql(graphene(,编写一个基于python/falcon的小应用程序,该应用程序返回帖子列表,包括REST&GraphQl:
from falcon import API, json
import graphene
def get_all_posts():
posts = [
{
'content': (
'Hello, '
"World..."
),
'author': 'Unknown author'
}
]
return posts
class Query(graphene.ObjectType):
posts = graphene.String()
def resolve_posts(self, info):
return get_all_posts()
schema = graphene.Schema(query=Query)
class PostsResource:
def on_get(self, req, resp):
posts = get_all_posts()
resp.media = {'posts': json.dumps(posts)}
class GraphQLResource:
def on_get(self, req, resp):
query = req.params['query']
result = schema.execute(query)
resp.media = result.data
api = API()
api.add_route('/graphql', GraphQLResource())
api.add_route('/posts', PostsResource())
查询 graphQl (localhost/graphql?query = query%20posts%20 {%20posts%20}(
态
使用休息终点(localhost/post(
{" posts":" [{{" content ":" Hello,world ... ","作者":"未知作者"}]"}
我不确定这是否重要,但是我想知道为什么序列序列不同?
尝试实现这一目标是有意义的吗?
任何帮助将不胜感激!谢谢!
- p.s如果我不倾倒(
json.dumps()
(我得到的剩余终点的结果:
{" posts":[{" content":"你好,世界...","作者":"未知作者"}]}
看起来它将整个帖子列表序列化为单字符串(posts = graphene.String()
(。我对graphene
不太熟悉,但您必须创建嵌套模式 - 类似的架构:
class Post(graphene.ObjectType):
content = graphene.String()
author = graphene.String()
class Query(graphene.ObjectType):
# or Field instead of List, I'm not sure about that.
posts = graphene.List(Post)
我希望它能帮助您继续解决问题