python异步向OSS上传图片示例

2019-03-23  本文已影响0人  Curious1990
import asyncio
import aiohttp
import oss2

auth = oss2.Auth('<>', '<>')
bucket = oss2.Bucket(auth, '<>', '<>')


def parser(url, res):
    result = bucket.put_object(f'test/{url[1]}', res)
    print(result.status)


async def downloader(url, callback=parser):
    async with aiohttp.ClientSession() as session:
        response = await session.get(url[0])
        if response.reason == 'OK':
            result = await response.read()
            callback(url, result)


if __name__ == '__main__':
    tasks = [
        downloader(['https://sc02.alicdn.com/kf/UT8uwlJX44aXXagOFbX8/Wholesale-cheap-slim-fit-leather-jacket-women.jpg',
                    '111.jpg']),
        downloader(['https://sc02.alicdn.com/kf/UT8j9RJX1RaXXagOFbXi/Wholesale-cheap-slim-fit-leather-jacket-women.jpg',
                    '222.jpg']),
    ]

    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.wait(tasks))
    loop.close()
上一篇下一篇

猜你喜欢

热点阅读