'how to make loop async in python
async def get_post_from_channel(channel, dateframe):
try:
my_channel = await client.get_entity(channel)
except (ValueError, telethon.errors.rpcerrorlist.UsernameInvalidError):
return 0
result = []
utc = pytz.UTC
async for msg in client.iter_messages(my_channel):
if msg.date > utc.localize(datetime.datetime.today() - timedelta(dateframe)):
result.append(msg)
return len(result)
async def get_posts_num(tg_urls, dateframe):
post_info = {}
for i in tg_urls:
num = await get_post_from_channel(i, dateframe)
post_info.update({i: num})
print({i: num})
with open(f'post_stat{dateframe}.json', 'w') as outfile:
json.dump(post_info, outfile)
I have 2 async functions. The first one is auxiliry and is used in second get_posts_num
function in loop. I can use a normal for loop but then my code will act synchronously and I lose the benefits and speed of having an async response fetching function.
Is there any way I can convert a list such that the above works? I just need to change the list's iter() to a aiter() method right? Can this be achieved by subclassing a list? Maybe encapsulating it in a class?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|