Skip to content

Instantly share code, notes, and snippets.

@WaffleLapkin
Created October 27, 2018 08:02
Show Gist options
  • Save WaffleLapkin/021981ff4d0406dd1ac95daf5366185c to your computer and use it in GitHub Desktop.
Save WaffleLapkin/021981ff4d0406dd1ac95daf5366185c to your computer and use it in GitHub Desktop.
import asyncio
from typing import Optional
import aiohttp
from aiohttp import ClientSession
class KittensQueue(asyncio.Queue):
def __init__(self, config, loop: asyncio.AbstractEventLoop, maxsize=15, mime_types: Optional[str] = "jpg"):
self.config = config
self._loop = loop
self.mime_types = mime_types
tasks = asyncio.gather(*[self.__put_new_cat() for _ in range(maxsize)])
asyncio.wait(tasks, loop=self._loop) # `asyncio.wait` - корутина и я не знаю как это работало раньше
super(KittensQueue, self).__init__(maxsize=maxsize, loop=loop)
async def __get_cat(self, size: Optional[str] = "full"):
url = self.config["urls"]["pic"]
api_key = self.config["urls"]["api-key"]
params_ = {"format": "json", "mime_types": self.mime_types, "size": size, "limit": "1"}
headers = {'Content-Type': "application/json", 'x-api-key': api_key}
async with ClientSession() as session:
session: aiohttp.ClientSession = session
async with session.get(url, headers=headers, params=params_) as resp:
return await resp.json()
async def __put_new_cat(self):
cat = await self.__get_cat()
await self.put(cat)
async def get(self):
self._loop.create_task(self.__put_new_cat())
return await super(KittensQueue, self).get()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment