python发出后文件请求

时间:2019-02-21 07:01:04

标签: python python-asyncio quart

大家好,我正在开发一个Python 3 quart异步应用程序,我正在尝试围绕我的http API设置一个测试框架。

Quart有一些方法可以构建json,form和raw请求,但是没有文件请求。我相信我需要自己构建请求包并发布“原始”请求。 使用邮递员,我可以看到请求看起来像这样:

----------------------------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进行发送?

我尝试使用夸脱请求:

    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'})

任何建议将不胜感激。

干杯。米奇。

1 个答案:

答案 0 :(得分:0)

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

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)
相关问题