python 发出 post 文件请求

python making a post file request

大家好,我正在开发一个 Python 3 夸脱异步应用程序,我正在尝试围绕我的 http API.

设置一个测试框架

Quart 具有构建 json、表单和原始请求但没有文件请求的方法。我相信我需要自己构建请求数据包和 post 一个 "raw" 请求。 使用 postman 我可以看到请求需要如下所示:

----------------------------298121837148774387758621\r\n
Content-Disposition: form-data; name="firmware"; filename="image.bin"\r\n
Content-Type: application/octet-stream\r\n
\r\n
\x00@\x00\x10\x91\xa0\t\x08+\xaa\t\x08/\xaa\t\x083\xaa\t\x087\xaa\t\x08;\xaa\t\x08\x00\x00\x00\
....
\xff\xff\xff\xff\xff\xff\xff\xa5\t\tZ\x0c\x00Rotea MLU Main V0.12\x00\x00k%\xea\x06\r\n
----------------------------298121837148774387758621--\r\n

如果有一种方法,我不想自己编码。

Python 中是否有一个模块,我可以在其中构建原始数据包数据并使用 Quart API 发送它?

我尝试过使用 quart 请求:

    import requests
    from .web_server import app as quart_app

    test_client = quart_app.test_client()
    firmware_image = 'test.bin'
    with open(firmware_image, 'rb') as f:
        data = f.read()
    files = {'firmware': (firmware_image, data , 'application/octet-stream')}
    firmware_req = requests.Request('POST', 'http://localhost:5000/firmware_update', files=files).prepare()
    response = await test_client.post('/firmware_update',
                                      data=firmware_req.body,
                                      headers={'Content-type': 'multipart/form-data'})

如有任何建议,我们将不胜感激。

干杯。米奇.

Python 的请求模块提供了一个准备函数,您可以使用它来获取它将为请求发送的原始数据。

import requests

url = 'http://localhost:8080/'
files = {'file' : open('z',  'rb'),
         'file2': open('zz', 'rb')}

req = requests.Request('POST',url, files=files)
r = req.prepare()
print(r.headers)
print(r.body)