【问题标题】:Sending nested json data with Python requests and in x-www-form-urlencoded使用 Python 请求和 x-www-form-urlencoded 发送嵌套的 json 数据
【发布时间】:2017-01-04 14:17:42
【问题描述】:

我不知道该怎么做。基本上一个特定的 API 要求

'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'

但他们希望表单数据是这样的:

stockLevels=[
  {
    "SKU": "sample string 1",
    "LocationId": "de0f1890-0c49-4834-b8cd-8b766fba496a",
    "Level": 3
  },
  {
    "SKU": "sample string 1",
    "LocationId": "de0f1890-0c49-4834-b8cd-8b766fba496a",
    "Level": 3
  }
]

我正在做的是这样的:

def change_stock_quantity(self, SKU, qty):
    # Note that this will change quantity of just one item
    # instead of two like in the example above
    payload = {
        'stockLevels':[{
          'SKU': SKU,
          'LocationId': self.ebay1_location_id,
          'Level': qty,
        }]
    }
    r = self.session.post(self.session_server + '//api/Stock/SetStockLevel',
                  data=payload)

    print r.request.body
    # stockLevels=SKU&stockLevels=LocationId&stockLevels=Level
    # this is not correct, it should be something like:
    # stockLevels:[{"SKU":"P01", "LocationId":"00000000", "Level":4}]

    print r
    # <Response [400]> (obivously)

关于我做错了什么有什么想法吗?

【问题讨论】:

  • 获得相关 API 文档的链接?编辑:是这个吗? apps.linnworks.net/Api/Method/Stock-SetStockLevel 如果是这样,示例可能是错误的,即他们实际上期望 JSON 正文。试试原始的,例如使用 CURL,看看哪些组合有效。
  • 我实际上解决了它,并将在下面发布回复。他们确实期待x-www-form-urlencoded。
  • 酷,我也同时做了一些研究 :)

标签: python json python-requests


【解决方案1】:

挖掘了这个GitHub repo's examples之后,他们的做法似乎是这样的:

  1. 身体确实是x-www-form-urlencoded
  2. 复杂参数是为x-www-form-urlencoded 编码的 JSON 字符串

所以查看their PHP example 的CreateVariationGroup 调用,试试这个:

stockLevels=[
  {
    "SKU": "sample string 1",
    "LocationId": "de0f1890-0c49-4834-b8cd-8b766fba496a",
    "Level": 3
  },
  {
    "SKU": "sample string 1",
    "LocationId": "de0f1890-0c49-4834-b8cd-8b766fba496a",
    "Level": 3
  }
]

payload = {'stockLevels' : json.dumps(stockLevels)}

# send payload encoded with x-www-form-urlencoded

【讨论】:

  • 是的,这正是我发现的。让我烦恼的是,他们的一些 API 似乎不再工作(例如apps.linnworks.net//Api/Method/Inventory-AddImageToItem),我不确定我还能如何通过代码实际上传图像。一般来说,我对 API 很陌生,所以也许您可以建议我一些标准方法来查找给定服务器的可用 API?
  • 我通常使用文档和示例代码 - 无论是示例代码、我链接到的 PHP + C# 之类的“原生 API”,还是使用此 API 的现有代码。例如,有关 Linnworks API 的用法,请参阅 GitHub 上的“代码搜索”:github.com/search?q=linnworks&type=Code&utf8=%E2%9C%93
  • 啊,太有用了,谢谢!不幸的是,似乎没有人真正将 Python 与 Linnworks 一起使用。虽然我可以做一些 Java,但我对 C# 或 PHP 没有任何经验。无论哪种情况,我之所以为此烦恼,是因为我想要连接它的所有其他应用程序都已经用 Python 构建了,所以我将继续使用它。
  • 幸运的是,使用 Postman 和他们的网络应用程序,我可以获取他们为我需要的东西发送的所有 API - 例如。图片上传是通过api/Uploader/UploadFileFromUrl完成的,然后通过api/Inventory/UploadImagesToInventoryItem附加到项目上
猜你喜欢
  • 2017-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-27
  • 2014-03-30
  • 2018-03-24
  • 1970-01-01
  • 2018-12-25
相关资源
最近更新 更多