将Python字典转换为GraphQL查询字符串



我有一个GraphQL后端,它是用NodeJS编写的,通过它我可以通过突变添加内容。输入到该突变中的数据是通过Python脚本创建的。现在我有一个这样的字典:

{
'title': 'ContentTitle',
'description': 'content description',
'active': True,
'chapters': [
{
'title': 'chapter title',
'lessons': [
{
'title': 'lesson title',
'filePath': 'static-resource-path'
},
{
'title': 'lesson title 2',
'filePath': 'static-resource-path2'
}
]
}
]
}

我需要将其转换为如下所示的GraphQL查询:

mutation {
addContent(
title: "ContentTitle",
description: "content description",
active: true,
chapters: [
{
title: "chapter title",
lessons: [
{
title: "lesson title",
filePath: "static-resource-path"
},
{
title: "lesson title 2",
filePath: "static-resource-path2"
}
]
}
]
) {
success
}
}

是否有任何简单的方法将字典(通常具有正确的格式)转换为GraphQL字符串?

你可以使用graphql-query包。

下面的代码是你的问题的一个简单实现:

from typing import Any, Dict, List
from graphql_query import Argument, Operation, Query
example_dict = {
'title': 'ContentTitle',
'description': 'content description',
'active': True,
'chapters': [
{
'title': 'chapter title',
'lessons': [
{
'title': 'lesson title',
'filePath': 'static-resource-path'
},
{
'title': 'lesson title 2',
'filePath': 'static-resource-path2'
}
]
}
]
}
def scalar_argument(key: str, value: Any) -> Argument:
"""Generate an Argument in the following form
key: "value"
key: true
key: false
...
"""
if isinstance(value, str):
return Argument(name=key, value=f'"{value}"')
elif isinstance(value, bool):
return Argument(name=key, value=str(value).lower())
# your cases here...
def get_query_arguments(arguments_dict: Dict[str, Any]) -> List[Argument]:
query_arguments = []
for key, value in arguments_dict.items():
# processing of scalar values
if isinstance(value, str) or isinstance(value, bool):
query_arguments.append(scalar_argument(key, value))
# processing of list with objects
elif isinstance(value, list):
values = [get_query_arguments(obj) for obj in value]
query_arguments.append(Argument(name=key, value=values))
return query_arguments
target_mutation = Operation(
type="mutation",
queries=[
Query(
name="addContent",
arguments=get_query_arguments(example_dict),
fields=["success"]
)
]
)
print(target_mutation.render())
# mutation {
#   addContent(
#     title: "ContentTitle"
#     description: "content description"
#     active: true
#     chapters: [
#       {
#         title: "chapter title"
#         lessons: [
#           {
#             title: "lesson title"
#             filePath: "static-resource-path"
#           }
#           {
#             title: "lesson title 2"
#             filePath: "static-resource-path2"
#           }
#         ]
#       }
#     ]
#   ) {
#     success
#   }
# }

最新更新