如何在python中发出aiohtp post photo请求?

anhgbhbe  于 2023-04-10  发布在  Python
关注(0)|答案(1)|浏览(142)

我正在尝试上传一个文件到网站,但没有成功。我需要获取文件的uuid才能在vinted.hu.上创建帖子。cookie和头文件没有问题,只有请求:'(
需要任何帮助!
文件接受按钮

<input data_testid="add-photos-input" name="photos" class="u-hidden" type="file" accept="image/*" multiple="">

发送照片的分片代码

with open('data/post/213.jpg', 'rb') as file:
    async with session.post('https://www.vinted.hu/api/v2/photos',headers=headers, data={"photos": file}) as response:
        print(await response.text())

结果

{"code":99,"message":"Sorry, there are some errors","message_code":"validation_error","errors":[{"field":"base","value":"param is missing or the value is empty: photo\nDid you mean?  photos"}],"payload":{}}

发送照片的piece code 1

data = FormData()
data.add_field('photos',open('data/post/213.jpg', 'rb'), filename='213.jpg', content_type='image/*')
async with session.post('https://www.vinted.hu/api/v2/photos',headers=headers, data=data) as response:
    print(await response.text())

结果1

{"code":99,"message":"Sorry, there are some errors","message_code":"validation_error","errors":[{"field":"base","value":"param is missing or the value is empty: photo\nDid you mean?  photos"}],"payload":{}}
rta7y2nd

rta7y2nd1#

在请求负载中使用multipart/form-data内容类型。

import aiohttp

async with aiohttp.ClientSession() as session:
    headers = {...}  # your headers here
    data = aiohttp.FormData()
    with open('data/post/213.jpg', 'rb') as f:
        data.add_field('photos', f, filename='213.jpg', content_type='image/jpeg')
    async with session.post('https://www.vinted.hu/api/v2/photos', headers=headers, data=data) as response:
        if response.status == 200:
            data = await response.json()
            # do something with the response
        else:
            # handle the error

相关问题