I have some code that I am using to scrape a url, parse the information, and then drop it into a DB using SQLAlchemy. I'm trying to do it asynchronously while limiting the maximum number of simultaneous requests.
Here is my code:
async def get_url(aiohttp_session, url1, url2):
async with session.get(url1) as r_url1:
if r_url1.status == 200:
async with session.get(url2) as r_url2:
if r_url2.status == 200:
return await r_url1.json(), await r_url2.json()
async def url_generator(formatted_start_date, formatted_end_date, machine_id, interval):
interval_start = formatted_start_date
interval_end = formatted_start_date + interval
while interval_end <= formatted_end_date:
yield (f"https://example.org/start={interval_start}"
f"Start={datetime.strftime(interval_start, DATETIME_FORMAT)}"
f"&End={datetime.strftime(interval_end, DATETIME_FORMAT)}"
f"&machines={machine_id}",
f"https://example.org/start={interval_start}"
f"Start={datetime.strftime(interval_start, DATETIME_FORMAT)}"
f"&End={datetime.strftime(interval_end, DATETIME_FORMAT)}"
f"&machines={machine_id}&groupby=Job"
)
interval_start += interval
interval_end += interval
async def parse(database, url1_json, url2_json):
""" Do some parsing and save it using credentials stored in the database object """
def main(database, formatted_start_date, formatted_end_date, machine_id, interval):
async for url1_json, url2_json in asyncio.as_completed(url_generator(formatted_start_date, formatted_end_date, machine_id, interval)):
parse(database, url1_json, url2_json)
I am getting the error yield from should be used as context manager expression.
I've tried looking at the documentation here as well as the Synchronization Primitives and am still confused as to where I've gone wrong and how I should go about creating tasks from my generator.