从Python字典列表构造GraphQL调用字符串

toiithl6  于 2022-12-17  发布在  Python
关注(0)|答案(1)|浏览(146)

我正在使用Python requests 库来执行GraphQL变异。我需要向 requests 库传递一个查询参数,该参数应包含一个字符串,该字符串应根据Python字典的Python列表构造。
Python字典列表看起来像这样:

my_list_of_dicts = [{"custom_module_id": "23", "answer": "some text 2", "user_id": "111"}, 
                            {"custom_module_id": "24", "answer": "a", "user_id": "111"}]

现在我需要把这个字典列表转换成一个字符串,这样它看起来就像这样:

my_list_of_dicts = [{custom_module_id: "23", answer: "some text 2", user_id: "111"}, 
                            {custom_module_id: "24", answer: "a", user_id: "111"}]

基本上,我需要得到一个看起来像Python字典列表的字符串,只是字典的键在字典键名周围没有引号。我这样做了,它工作了:

my_query_string = json.dumps(my_list_of_dicts).replace("\"custom_module_id\"", "custom_module_id")
my_query_string = my_query_string.replace("\"answer\"", "answer")
my_query_string = my_query_string.replace("\"user_id\"", "user_id")

但是我想知道是否有更好的方法来实现这个目标?我所说的“更好”是指一些函数调用,它将为准备使用的GraphQL字符串准备json/dictionary格式。

bcs8qyzn

bcs8qyzn1#

我想这可能会帮助你找到你的最终答案。Follow this article

gq = """
mutation ReorderProducts($id: ID!, $moves: [MoveInput!]!) {
    collectionReorderProducts(id: $id, moves: $moves) {
        job {
            id
            }
            userErrors {
                field
                message
            }
        }
    }
"""
resp = self.sy_graphql_client.execute(
    query=gq,
    variables={
        "id": before_collection_meta.coll_meta.id,
        "moves": list(map(lambda mtc:
            {
                "id": mtc.id, "newPosition": mtc.new_position
            }, move_to_commands))
    }
)

reorder_job_id = resp["data"]["collectionReorderProducts"]["job"]["id"]
self.sy_graphql_client.wait_for_job(reorder_job_id)

相关问题