aiohttp test
toml
[tool.poetry.dependencies]
python = "^3.9"
aiohttp = "^3.9.1"
aiofiles = "^23.2.1"
python
import asyncio
import aiofiles
import aiohttp
import os
class Producer:
def __init__(self, dir_d):
self.dir_d = self.create_directory(dir_d)
@staticmethod
def create_directory(dir_d):
if not os.path.exists(dir_d):
os.mkdir(dir_d)
print(f'[+] Created directory {dir_d}')
return dir_d
class ImageDownloader:
def __init__(self):
self.headers = {'user-agent': 'Python/3.9 aiohttp/3.9.1'}
async def write_file(self, filename, content):
async with aiofiles.open(filename, mode='wb') as f:
await f.write(content)
async def request(self, url, filename):
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=self.headers) as response:
print(dict(response.request_info.headers))
content = await response.read()
# print('[+] get file size', len(content))
await self.write_file(filename, content)
def start(self):
url = 'http://wx2.sinaimg.cn/mw600/0089jzyPly1gqo2l5gwb7j31400u04qp.jpg'
filename = os.path.join(Producer('download/').dir_d, '0.jpg')
asyncio.run(self.request(url, filename))
def main():
downloader = ImageDownloader()
downloader.start()
if __name__ == '__main__':
main()