【问题标题】:Can't post JSON files with iglob?无法使用 iglob 发布 JSON 文件?
【发布时间】:2014-05-28 17:10:20
【问题描述】:

我可以通过执行以下操作来发布 一个 json 文件:

url = 'https://myWebsite.com/ext/ext/ext'
json_file = open("/Users/ME/folder/folder/folder/folder/test.json")

headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json_file, headers=headers)

但是当我尝试使用 iglob 遍历目录中的所有 json 文件时:

url = 'https://myWebsite.com/ext/ext/ext'
json_files = glob.iglob("/Users/ME/Documents/folder/folder/folder/*.json")

for data in json_files:
    test = {'file': open(data)}
    headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
    r = requests.post(url, data=test, headers=headers)

服务器向我抛出了一些疯狂的错误,表明我发布了无效的 JSON 原语。我对这两种方法都使用了 exact 相同的 json 文件,但由于某种原因,第二种方法失败了。

【问题讨论】:

  • 您是否尝试过 打印 json_files 并查看您是否真的打开了相同的文件?
  • print json_files = "" and print json_file = ""
  • 我不太确定这意味着什么,但我知道它们是同一个文件,只是访问方式不同
  • iglob() 返回一个生成器,在循环对象时按需生成文件名。 print list(json_files) 为您提供所有匹配项的列表。不过没关系,我发现了问题。

标签: python json python-requests glob


【解决方案1】:

你不应该在这里使用字典:

for data in json_files:
    test = open(data)
    headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
    r = requests.post(url, data=test, headers=headers)

当为data 使用字符串或打开文件对象以外的任何内容时,您最终会发布一个application/x-www-form-urlencoded 内容主体,因为requests 会为您编码请求主体。您只想发布文件的内容,因为您想发送 application/json 正文。

请注意,在您的单个文件测试中,您也没有使用字典。

最好将打开的文件用作上下文管理器,以确保它再次关闭:

for data in json_files:
    headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
    with open(data) as test:
        r = requests.post(url, data=test, headers=headers)

【讨论】:

  • 谢谢。这解决了问题。我在之前的代码块中使用了字典,这次抓取的是一堆“.txt”文件而不是“.json”文件。无论如何,这个字典语法是否特定于文件扩展名?
  • @user3175426:它特定于您要发送的 内容类型。如果您给data 提供除字符串以外的任何内容,它会为您将其编码为application/x-www-form-urlencoded 字符串(当您发布表单时浏览器会执行此操作)。
  • @user3175426:但是,您不会发送application/x-www-form-urlencoded 正文。您正在发送application/json,它恰好与您的文件内容相匹配。
  • @user3175426:如果你想发布text/plain,那么你也不会对正文进行编码。
  • 我明白了。以后我会更加注意如何发布不同的文件类型。非常感谢你的帮助! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-16
  • 1970-01-01
  • 1970-01-01
  • 2011-04-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多