我想使用aiohttp多帖子。 而且,我需要发布FILE。 但是,我的代码无法正常工作 这是我的代码
import aiohttp
file = open('file/path', 'rb')
async with aiohttp.request('post', url, files=file) as response:
return await response.text()
和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'
请....这个可能...? 我需要解决方案...请... T ^ T
这是期望的输出
request.FILES['key'] == file
密钥为html格式
<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>
谢谢!它运作良好!
但是我还有更多问题
我正在使用from django.core.files.uploadedfile import InMemoryUploadedFile
这是我使用py.test
def get_uploaded_file(file_path):
f = open(file_path, "rb")
file = DjangoFile(f)
uploaded_file = InMemoryUploadedFile(file, None, file_path, "text/plain", file.size, None, None)
return uploaded_file
file = get_uploaded_file(path)
async with aiohttp.request('post', url, data={'key': f}) as response:
return await response.text()
如何在测试中编写此代码...?
答案 0 :(得分:2)
根据POST a Multipart-Encoded File - Client Quickstart - aiohttp documentation,您需要将文件指定为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)
注意:字典关键字应为key
,以匹配key
中的<input type="file" name="key" id="file" />
答案 1 :(得分:0)
客户端:
import requests
url = 'http://SERVER_ADDRESS:PORT/sendfile'
files = {'file': open('data.txt', 'r').read()}
requests.post(url, data=files)
服务器:
from aiohttp import web
PORT = 8082
async def send_file(request):
data = await request.post()
with open('data.txt', 'w') as f:
f.write(data['file'])
return web.Response(text='ok',content_type="text/html")
app = web.Application(client_max_size=1024**3)
app.router.add_post('/sendfile', send_file)
web.run_app(app,port=PORT)
答案 2 :(得分:0)
对于接收二进制数据,您可以使用 read
请求函数。
例如接收一个文本文件将如下所示:
from aiohttp import web
async def receive_post_request(request)
data = (await request.read()).decode('utf-8')
return web.Response(text='data', content_type="text/html")