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

AIOHTTP

 

一、文件上傳html

① 單個文件上傳python

服務端web

 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))

客戶端session

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

    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()

客戶端oop

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())
相關文章
相關標籤/搜索