aiohttp web provides file download service

Keywords: Python Session

python3.6
Using aiohttp, aiofiles library, asynchronous operation
The server code is as follows. After starting the service, it will listen to 0.0.0.0:8080 by default
No exception handling, applicable to small files, for reference only

file_server.py:

import aiofiles
import asyncio
import os
from aiohttp.web import Response
from aiohttp import web

def query_parse(req):
    obj = req.query_string
    queryitem = []
    if obj:
        query = req.query.items()
        for item in query:
            queryitem.append(item)
        return dict(queryitem)
    else:
        return None

async def download(request):
    query = query_parse(request)
    filename = query.get('file')
        # There is no exception handling. Only when the / tmp/files directory exists on the server and the requested file is in the directory, can it be downloaded normally
    file_dir = '/tmp/files'
    file_path = os.path.join(file_dir, filename)
    if os.path.exists(file_path):
        async with aiofiles.open(file_path, 'rb') as f:
            content = await f.read()
        if content:
            response = Response(
                content_type='application/octet-stream',
                headers={'Content-Disposition': 'attachment;filename={}'.format(filename)},
                body=content
                            )
            return response

        else:
            return
    else:
        return

loop = asyncio.get_event_loop()
app = web.Application(loop=loop)
app.router.add_route(method='get', path='/download', handler=download)
web.run_app(app)
loop.close()

python3 file_server.py running server

The client code is as follows:
download.py:

import aiohttp
import asyncio
import aiofiles

# Visit the download interface function of the server and download the file l5u.jpg under the specified directory (/ tmp/files /) on the server
url = 'http://localhost:8080/download'
params = {'file': 'l5u.jpg'}

async def download():
    async with aiohttp.ClientSession() as session:
        async with session.get(url, params=params) as resp:
            content = await resp.content.read()
        async with aiofiles.open('/tmp/test.jpg', 'wb') as f:
            await f.write(content)

loop = asyncio.get_event_loop()
loop.run_until_complete(download())

Execute python3 download.py to check whether / tmp/test.jpg exists and whether opening is normal
Or directly visit http://localhost:8080/download?file=l5u.jpg with a browser. The name of the downloaded file is the same as the name of the file requested to be sent (the name of the file existing on the server)

Posted by LarryK on Sat, 07 Dec 2019 17:50:42 -0800