【问题标题】:Constructing GraphQL call string from Python list of dictionaries从 Python 字典列表构造 GraphQL 调用字符串
【发布时间】:2022-12-13 12:57:48
【问题描述】:

我正在使用 Python要求执行 GraphQL 突变的库。我需要通过要求library 一个查询参数,它应该包含一个字符串,该字符串应该从 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/字典格式。

【问题讨论】:

    标签: python string graphql


    【解决方案1】:

    我认为这可以帮助您找到最终答案。 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-29
      • 1970-01-01
      • 2017-12-15
      相关资源
      最近更新 更多