From 1f116850ce7c43cecb00bbc7dd547979dff1bc5a Mon Sep 17 00:00:00 2001 From: April Date: Sun, 13 Nov 2022 15:52:15 -0700 Subject: [PATCH] AirQuality to asynchronous --- recordGenerators/AirQuality.py | 35 ++++++++++++++++++---------------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/recordGenerators/AirQuality.py b/recordGenerators/AirQuality.py index cb09528..8334783 100644 --- a/recordGenerators/AirQuality.py +++ b/recordGenerators/AirQuality.py @@ -4,6 +4,7 @@ import os import shutil import xml.dom.minidom import logging,coloredlogs +import aiohttp, aiofiles l = logging.getLogger(__name__) coloredlogs.install() @@ -27,22 +28,24 @@ for i in MPC.getPrimaryLocations(): apiKey = '21d8a80b3d6b444998a80b3d6b1449d3' -def getData(epaId, zipcode): +async def getData(epaId, zipcode): url = f"https://api.weather.com/v1/location/{zipcode}:4:US/airquality.xml?language=en-US&apiKey={apiKey}" + data = "" - res = requests.get(url=url) - - data = res.text + async with aiohttp.ClientSession() as s: + async with s.get(url) as r: + data = await r.text() + newData = data[57:-11] # Write to i2doc file i2Doc = f'' + '' + newData + f'{epaId}' - f = open("./.temp/AirQuality.i2m", 'a') - f.write(i2Doc) - f.close() + async with aiofiles.open("./.temp/AirQuality.i2m", 'a') as f: + await f.write(i2Doc) + await f.close() -def writeData(): +async def writeData(): useData = False workingEpaIds = [] @@ -62,21 +65,21 @@ def writeData(): header = '' footer = "" - with open("./.temp/AirQuality.i2m", 'w') as doc: - doc.write(header) + async with aiofiles.open("./.temp/AirQuality.i2m", 'w') as doc: + await doc.write(header) for (x, y) in zip(workingEpaIds, zipCodes): - getData(x, y) + await getData(x, y) - with open("./.temp/AirQuality.i2m", 'a') as end: - end.write(footer) + async with aiofiles.open("./.temp/AirQuality.i2m", 'a') as end: + await end.write(footer) dom = xml.dom.minidom.parse("./.temp/AirQuality.i2m") xmlPretty = dom.toprettyxml(indent = " ") - with open("./.temp/AirQuality.i2m", 'w') as g: - g.write(xmlPretty[23:]) - g.close() + async with aiofiles.open("./.temp/AirQuality.i2m", 'w') as g: + await g.write(xmlPretty[23:]) + await g.close() files = [] commands = []