Python 3使用仅标准库发送带文件的请求。

huangapple go评论118阅读模式
英文:

Python 3 send a request with a file using only standard libraries

问题

以下是已翻译的内容:

所以,我有以下使用 requests 库工作的代码:

file_test = {'file': ('test.json', open('C:/Users/abc/test.json', 'rb'), 'application/json')}

response = requests.post(url, files=file_test, verify=False)

这段代码按预期工作。但最近公司要求我们只使用标准库。所以,我尝试使用 http.client 库来完成完全相同的事情:

httpHost = 'some host'
uri = 'some uri'
conn = http.client.HTTPSConnection(httpHost, context=ssl._create_unverified_context())
with open('C:/Users/abc/test.json', 'rb') as file:
    f = file.read()
headers = {
    'Content-Type': 'multipart/form-data; boundary=TESTabc123',
    'Content-Length': str(len(f)),
    'Accept': '*/*'
}
conn.request(verb, uri, body=f, headers=headers)
print(conn.getresponse().status)

然而,使用上述代码我得到了一个 500 的状态码。值得一提的是,头部部分我从 Postman 中提取了完全相同的内容(在 Postman 中,我使用相同的文件和相同的头部能够获得 200 的状态码)。

我是否做得正确?似乎我按照一切正确的方式进行操作,但仍然得到了不希望的结果。我还尝试过使用 urllib 的 request 库,但似乎 verify=False 部分在那里不起作用。

我唯一能想到的是请求内容长度,因为在 Postman 中,当提供错误的长度时也会导致 500 错误。

英文:

So I have the following Code which is working using the requests library:

file_test = {'file': ('test.json', open('C:/Users/abc/test.json','rb'), 'application/json')}

response = requests.post(url, files=file_test, verify=False)

which works as expected. But recently company want us to use only standard libraries. So I went ahead to try out http.client library to accomplish the exact same thing:

httpHost = 'some host'
uri = 'some uri'
conn = http.client.HTTPSConnection(httpHost,context = ssl._create_unverified_context())
with open('C:/Users/abc/test.json','rb') as file:
    f = file.read()
headers = {
    'Content-Type': 'multipart/form-data; boundary=TESTabc123',
    'Content-Length': str(len(f)),
    'Accept' : '*/*'
}  
conn.request(verb, uri, body=f, headers=headers)
print(conn.getresponse().status)

However, I am hitting a 500 status code with the above code. Just to mention, the headers part I pulled the exact same thing from postman (I was able to get a 200 on postman with the same file and same headers).

Am I doing this thing correctly? It seems like I followed everything correctly but still getting undesired results. I also tried with urllib's request library but seems like the verify=False part doesn't work on there.

The only thing I can think of is the request content length, which in postman, also gives a 500 error when wrong length is provided.

答案1

得分: 0

根据请求文档,Content-Length应该是文件中的字节数,而不是文本的长度,请尝试将'Content-Length': str(len(f)),更改为'Content-Length': len(f),
还请确保verb = post。

让我知道是否有帮助 - Jack

英文:

According to the requests documentation, the Content-Length should be the number of bytes in the file, not the length of the text, could you try changing 'Content-Length': str(len(f)), to 'Content-Length': len(f),.
Also make sure verb = post.

Let me know if that Helps - Jack

答案2

得分: 0

import http.client
import ssl

httpHost = '一些主机'
uri = '一些URI'
boundary = 'TESTabc123'

conn = http.client.HTTPSConnection(httpHost, context=ssl._create_unverified_context())

with open('C:/Users/abc/test.json', 'rb') as file:
    f = file.read()

body = (
    f'--{boundary}\r\n'
    f'Content-Disposition: form-data; name="file"; filename="test.json"\r\n'
    'Content-Type: application/json\r\n\r\n'
    f'{f.decode()}\r\n'
    f'--{boundary}--\r\n'
)

headers = {
    'Content-Type': f'multipart/form-data; boundary={boundary}',
    'Content-Length': str(len(body)),
    'Accept': '*/*'
}

conn.request('POST', uri, body=body, headers=headers)
print(conn.getresponse().status)
英文:
import http.client
import ssl

httpHost = 'some host'
uri = 'some uri'
boundary = 'TESTabc123'

conn = http.client.HTTPSConnection(httpHost, 
context=ssl._create_unverified_context())

with open('C:/Users/abc/test.json', 'rb') as file:
    f = file.read()

body = (
    f'--{boundary}\r\n'
    f'Content-Disposition: form-data; name="file"; filename="test.json"\r\n'
    'Content-Type: application/json\r\n\r\n'
    f'{f.decode()}\r\n'
    f'--{boundary}--\r\n'
)

    headers = {
    'Content-Type': f'multipart/form-data; boundary={boundary}',
    'Content-Length': str(len(body)),
    'Accept': '*/*'
}

conn.request('POST', uri, body=body, headers=headers)
print(conn.getresponse().status)                                                

I think this will be better

huangapple
  • 本文由 发表于 2023年8月9日 13:41:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76864874-2.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定