lee
lee

Reputation: 63

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

Upvotes: 4

Views: 21748

Answers (4)

med
med

Reputation: 119

I solved using FormData as described in documentation:

data = FormData()
data.add_field('file',open('input.tsv', 'rb'), filename='input.tsv', content_type='text/tab-separated-values')
async with session.post(url, data=data) as resp:
    data = await resp.read()

Upvotes: 2

Arseniy Lebedev
Arseniy Lebedev

Reputation: 470

For receive binary data you can use read function of request.

For example receiving a text file will looks like:

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

Upvotes: 0

Alexey Yurasov
Alexey Yurasov

Reputation: 109

client:

import requests

url = 'http://SERVER_ADDRESS:PORT/sendfile'
files = {'file': open('data.txt', 'r').read()}
requests.post(url, data=files)

server:

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)

Upvotes: 2

falsetru
falsetru

Reputation: 369144

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

Upvotes: 5

Related Questions