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

  

转载于:https://www.cnblogs.com/lianzhilei/p/10126349.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值