From a2a05d24bf5570ae05f20d1f6a2c91c456ce7a5c Mon Sep 17 00:00:00 2001 From: Philipp Spitzer Date: Tue, 23 Sep 2025 19:39:13 +0200 Subject: [PATCH] Use with statement for connection resource handling. --- owm.py | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/owm.py b/owm.py index 307e910..1a55892 100755 --- a/owm.py +++ b/owm.py @@ -82,18 +82,17 @@ def write_db(config, url, weather_json, weather_data): db = config.get('database','database') engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'.format(user, pwd, host, db), echo=False) - conn = engine.connect() - row = dict(cityid=config.get('openweathermap', 'cityid'), url=url, result=json.dumps(weather_json)) - row.update(weather_data) - for key, value in row.items(): - if isinstance(value, float) and math.isnan(value): - row[key] = None - metadata = sqlalchemy.MetaData() - openweathermap_table = Table('openweathermap', metadata, autoload_with=engine) - ins = openweathermap_table.insert().prefix_with('IGNORE').values(**row) - conn.execute(ins) - conn.commit() - conn.close() + with engine.connect() as conn: + row = dict(cityid=config.get('openweathermap', 'cityid'), url=url, result=json.dumps(weather_json)) + row.update(weather_data) + for key, value in row.items(): + if isinstance(value, float) and math.isnan(value): + row[key] = None + metadata = sqlalchemy.MetaData() + openweathermap_table = Table('openweathermap', metadata, autoload_with=engine) + ins = openweathermap_table.insert().prefix_with('IGNORE').values(**row) + conn.execute(ins) + conn.commit() def main(configfile, debug): -- 2.47.3