lee*_*lee 4 python python-asyncio aiohttp
我想使用 aiohttp 进行多帖子。而且,我需要用文件发布。但是,我的代码不起作用这是我的代码
import aiohttp
file = open('file/path', 'rb')
async with aiohttp.request('post', url, files=file) as response:
return await response.text()
Run Code Online (Sandbox Code Playgroud)
和request.FILES is None
这是引用通告
def post(self, url: StrOrURL,
*, data: Any=None, **kwargs: Any) -> '_RequestContextManager':
"""Perform HTTP POST request."""
return _RequestContextManager(
self._request(hdrs.METH_POST, url,
data=data,
> **kwargs))
E TypeError: _request() got an unexpected keyword argument 'files'
Run Code Online (Sandbox Code Playgroud)
拜托....这可能...?我需要解决方案...请...T^T
这是所需的输出
request.FILES['key'] == file
关键是html形式
def post(self, url: StrOrURL,
*, data: Any=None, **kwargs: Any) -> '_RequestContextManager':
"""Perform HTTP POST request."""
return _RequestContextManager(
self._request(hdrs.METH_POST, url,
data=data,
> **kwargs))
E TypeError: _request() got an unexpected keyword argument 'files'
Run Code Online (Sandbox Code Playgroud)
谢谢!效果很好!但我有更多正在使用的问题from django.core.files.uploadedfile import InMemoryUploadedFile
,这是我使用 py.test 的测试代码
<form method="post" name="file_form" id="file_form" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="key" id="file" />
<input type="submit" />
</form>
Run Code Online (Sandbox Code Playgroud)
我怎样才能在测试中编写这段代码...?
根据POST a Multipart-Encoded File - Client Quickstart - aiohttp 文档,您需要将文件指定为data字典(值应该是类似文件的对象):
import asyncio
import aiohttp
async def main():
url = 'http://httpbin.org/anything'
with open('t.py', 'rb') as f:
async with aiohttp.ClientSession() as session:
async with session.post(url, data={'key': f}) as response:
return await response.text()
text = asyncio.run(main()) # Assuming you're using python 3.7+
print(text)
Run Code Online (Sandbox Code Playgroud)
注意:字典键应该key匹配key<input type="file" name="key" id="file" />