分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 运营维护

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

发布时间:2023-09-06 02:26责任编辑:胡小海关键词:http
python3.6
使用了aiohttp, aiofiles库,异步操作
服务端代码如下,启动服务后,默认监听0.0.0.0:8080
没有做任何异常处理,适用于小文件,仅供参考

file_server.py:

import aiofilesimport asyncioimport osfrom aiohttp.web import Responsefrom aiohttp import webdef 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 Noneasync 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: ???????returnloop = 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 aiohttpimport asyncioimport aiofiles# 访问服务端download接口函数,下载服务器上指定目录(/tmp/files/)下的文件l5u.jpgurl = ‘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, 下载下来的文件名称与请求发送的文件名称(服务器上存在的文件名称)一致

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

原文地址:http://blog.51cto.com/xiebingtang/2333025

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved