How to aiohttp request post files list python requests module?

I want to multi post using aiohttp. And, I need post with FILE. But, my code dosen't work This is my code

import aiohttp

file = open('file/path', 'rb')
async with aiohttp.request('post', url, files=file) as response:
   return await response.text()

and request.FILES is None

this is trackback

    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'

please.... this possbile...? i need solution... please...T^T

this is desired output

request.FILES['key'] == file

the key is in html form

<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>

thanks! it works well! But i have more questions I'm using from django.core.files.uploadedfile import InMemoryUploadedFile and this my test code using 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()

How can I make this code in test...?


Solution 1:

According to POST a Multipart-Encoded File - Client Quickstart - aiohttp documentation, you need to specify the file as data dictionary (value should be a file-like object):

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)

NOTE: dictionary key should be key to match key in <input type="file" name="key" id="file" />