如何使用 aiohttp 发送 miltipart/form-data

问题描述 投票:0回答:1

我需要像这样发送有效载荷:

--XXX
Content-Disposition: form-data; name="name"

John
--XXX
Content-Disposition: form-data; name="age"

12
--XXX--

我该怎么做?

我正在尝试这样做,但服务器返回

{'statusCode': 400, 'message': ['queueType must be a valid enum value', 'query must be a string'], 'error': 'Bad Request'}

async def run(self, query: str, queue_type: str = "generate", preset: str = '1', style: str = "") -> Run:
    url = "https://fusionbrain.ai/api/v1/text2image/run"
    boundary = uuid.uuid4().hex

    writer = aiohttp.MultipartWriter('form-data', boundary=boundary)
    writer.append(io.BytesIO(queue_type.encode("UTF-8")), {"Content-Disposition": 'form-data; name="queueType"'})
    writer.append(io.BytesIO(query.encode("UTF-8")), {"Content-Disposition": 'form-data; name="query"'})
    writer.append(io.BytesIO(preset.encode("UTF-8")), {"Content-Disposition": 'form-data; name="preset"'})
    writer.append(io.BytesIO(style.encode("UTF-8")), {"Content-Disposition": 'form-data; name="style"'})
    extra_headers = {'Content-Type': f"multipart/form-data; boundary={boundary}"}

    async with self._session.post(url, headers=self._headers | extra_headers, data=writer) as response:
        return Run.from_response(await response.json())
python multipart form-data aiohttp
1个回答
0
投票

我解决我的问题

我拿的是httpx,我的代码:

async def run(self, query: str, queue_type: str = "generate", preset: str = '1', style: str = "") -> Run:
    url = "https://fusionbrain.ai/api/v1/text2image/run"

    request_data = {
        "queueType": (None, queue_type),
        "query": (None, query),
        "preset": (None, preset),
        "style": (None, style)
    }

    response = await self._session.post(url, files=request_data, headers=self._headers)
    return Run.from_response(response.json())

然后问题出在 Bad Request 中,我通过添加 Referer 和 Origin 标头解决了它。

© www.soinside.com 2019 - 2024. All rights reserved.