aiohttp web方式提供文件下载服务

python3.6
使用了aiohttp, aiofiles库,异步操作
服务端代码如下,启动服务后,默认监听0.0.0.0:8080
没有做任何异常处理,适用于小文件,仅供参考

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')
        # 没有作任何异常处理,只有服务器上存在/tmp/files目录,并且请求的文件在该目录下,才能正常下载
    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 运行服务端

客户端代码如下:
download.py:

import aiohttp
import asyncio
import aiofiles

# 访问服务端download接口函数,下载服务器上指定目录(/tmp/files/)下的文件l5u.jpg
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())

执行python3 download.py,查看/tmp/test.jpg是否存在,打开是否正常
或者直接使用浏览器访问http://localhost:8080/download?file=l5u.jpg, 下载下来的文件名称与请求发送的文件名称(服务器上存在的文件名称)一致

猜你喜欢

转载自blog.51cto.com/xiebingtang/2333025