1. 程式人生 > >aiohttp web方式提供檔案下載服務

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, 下載下來的檔名稱與請求傳送的檔名稱(伺服器上存在的檔名稱)一致