1. 程式人生 > >Python開發【模組】:aiohttp(二)

Python開發【模組】:aiohttp(二)

AIOHTTP

 

1、檔案上傳

① 單個檔案上傳

服務端

 async def post(self, request):
        reader = await request.multipart()
        # /!\ 不要忘了這步。(至於為什麼請搜尋 Python 生成器/非同步)/!\
        file = await reader.next()
        filename = file.filename
        # 如果是分塊傳輸的,別用Content-Length做判斷。
        size = 0
        with open(filename, 'wb') as f:
            while True:
                chunk = await file.read_chunk()  # 預設是8192個位元組。
                if not chunk:
                    break
                size += len(chunk)
                f.write(chunk)

        return web.Response(text='{} sized of {} successfully stored'
                                 ''.format(filename, size))

客戶端

import aiohttp
import asyncio

url = 'http://127.0.0.1:8080/'
files = {'file': open('files/1M.wav', 'rb'),}

async def fetch(session, url):
    async with session.post(url,data=files) as response:
        return await response.text()


async def main():
    async with aiohttp.ClientSession() as session:
        html = await fetch(session, 'http://127.0.0.1:8080')
        print(html)


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

 ② 傳輸多個檔案及其他引數

服務端

    async def post(self, request):
        reader = await request.multipart()
        data = {}
        async for read in reader:
            filename = read.filename
            if filename is not None:
                size = 0
                with open('./' + filename, 'wb') as f:
                    while True:
                        chunk = await read.read_chunk()  # 預設是8192個位元組。
                        if not chunk:
                            break
                        size += len(chunk)
                        f.write(chunk)
            else:
                value = await read.next()
                key = read.name
                data[key] = str(value, encoding='utf-8')
        print(data)
        return web.Response()

客戶端

import aiohttp
import asyncio

url = 'http://127.0.0.1:8080/'
files = {'file': open('files/1M.wav', 'rb'),
         'file2': open('files/0.5M.wav', 'rb'),
         'name':'000001',
         }

async def fetch(session, url):
    async with session.post(url,data=files) as response:
        return await response.text()


async def main():
    async with aiohttp.ClientSession() as session:
        html = await fetch(session, 'http://127.0.0.1:8080')
        print(html)


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