Skip to content

Commit

Permalink
Use context manager to connect to the database
Browse files Browse the repository at this point in the history
  • Loading branch information
benoitblanc authored and manisandro committed Aug 8, 2024
1 parent a81713f commit 4ce683c
Showing 1 changed file with 41 additions and 42 deletions.
83 changes: 41 additions & 42 deletions src/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,7 @@ def db_conn():
user_bookmark_table = config.get('user_bookmark_table', 'qwc_config.user_bookmarks')

db = db_engine.db_engine(db_url)
conn = db.connect()
return (conn, permalinks_table, user_permalink_table, user_bookmark_table)
return (db, permalinks_table, user_permalink_table, user_bookmark_table)


@api.route('/createpermalink')
Expand Down Expand Up @@ -95,7 +94,7 @@ def post(self):
}

# Insert into databse
configconn, permalinks_table, user_permalink_table, user_bookmark_table = db_conn()
db_engine, permalinks_table, user_permalink_table, user_bookmark_table = db_conn()
datastr = json.dumps(data)
hexdigest = hashlib.sha224((datastr + str(time.time())).encode('utf-8')).hexdigest()[0:9]
date = datetime.date.today().strftime(r"%Y-%m-%d")
Expand All @@ -112,7 +111,8 @@ def post(self):
attempts = 0
while attempts < 100:
try:
configconn.execute(sql, {"key": hexdigest, "data": datastr, "date": date, "expires": expires})
with db_engine.begin() as connection:
connection.execute(sql, {"key": hexdigest, "data": datastr, "date": date, "expires": expires})
break
except:
pass
Expand All @@ -124,10 +124,8 @@ def post(self):
DELETE FROM {table}
WHERE expires < CURRENT_DATE
""".format(table=permalinks_table))
configconn.execute(sql)

configconn.commit()
configconn.close()
with db_engine.begin() as connection:
connection.execute(sql)

# Return
if attempts < 100:
Expand All @@ -150,14 +148,15 @@ def get(self):
args = resolvepermalink_parser.parse_args()
key = args['key']
data = {}
configconn, permalinks_table, user_permalink_table, user_bookmark_table = db_conn()
db_engine, permalinks_table, user_permalink_table, user_bookmark_table = db_conn()
sql = sql_text("""
SELECT data
FROM {table}
WHERE key = :key AND (expires IS NULL OR expires >= CURRENT_DATE)
""".format(table=permalinks_table))
try:
data = json.loads(configconn.execute(sql, {"key": key}).mappings().first()["data"])
with db_engine.connect() as connection:
data = json.loads(connection.execute(sql, {"key": key}).mappings().first()["data"])
except:
pass
return jsonify(data)
Expand All @@ -172,14 +171,15 @@ def get(self):
if not username:
return jsonify({})

configconn, permalinks_table, user_permalink_table, user_bookmark_table = db_conn()
db_engine, permalinks_table, user_permalink_table, user_bookmark_table = db_conn()
sql = sql_text("""
SELECT data
FROM {table}
WHERE username = :user
""".format(table=user_permalink_table))
try:
data = json.loads(configconn.execute(sql, {"user": username}).mappings().first()["data"])
with db_engine.connect() as connection:
data = json.loads(connection.execute(sql, {"user": username}).mappings().first()["data"])
except:
data = {}
return jsonify(data)
Expand Down Expand Up @@ -213,7 +213,7 @@ def post(self):
}

# Insert into databse
conn, permalinks_table, user_permalink_table, user_bookmark_table = db_conn()
db_engine, permalinks_table, user_permalink_table, user_bookmark_table = db_conn()
datastr = json.dumps(data)
date = datetime.date.today().strftime(r"%Y-%m-%d")
sql = sql_text("""
Expand All @@ -225,9 +225,8 @@ def post(self):
SET data = :data, date = :date
""".format(table=user_permalink_table))

conn.execute(sql, {"user": username, "data": datastr, "date": date})
conn.commit()
conn.close()
with db_engine.begin() as connection:
connection.execute(sql, {"user": username, "data": datastr, "date": date})

return jsonify({"success": True})

Expand All @@ -244,22 +243,23 @@ def get(self):
config = config_handler.tenant_config(tenant)
sort_order = config.get('bookmarks_sort_order', 'date, description')

conn, permalinks_table, user_permalink_table, user_bookmark_table = db_conn()
db_engine, permalinks_table, user_permalink_table, user_bookmark_table = db_conn()
sql = sql_text("""
SELECT data, key, description, to_char(date, 'YYYY-MM-DD') as date
FROM {table}
WHERE username = :user ORDER BY {sort_order}
""".format(table=user_bookmark_table, sort_order=sort_order))
try:
data = []
result = conn.execute(sql, {"user": username}).mappings()
for row in result:
bookmark = {}
bookmark['data'] = json.loads(row.data)
bookmark['key'] = row.key
bookmark['description'] = row.description
bookmark['date'] = row.date
data.append(bookmark)
with db_engine.connect() as connection:
result = connection.execute(sql, {"user": username}).mappings()
for row in result:
bookmark = {}
bookmark['data'] = json.loads(row.data)
bookmark['key'] = row.key
bookmark['description'] = row.description
bookmark['date'] = row.date
data.append(bookmark)
except:
data = []
return jsonify(data)
Expand Down Expand Up @@ -294,7 +294,7 @@ def post(self):
}

# Insert into database
conn, permalinks_table, user_permalink_table, user_bookmark_table = db_conn()
db_engine, permalinks_table, user_permalink_table, user_bookmark_table = db_conn()
datastr = json.dumps(data)
hexdigest = hashlib.sha224((datastr + str(time.time())).encode('utf-8')).hexdigest()[0:9]
date = datetime.date.today().strftime(r"%Y-%m-%d")
Expand All @@ -312,15 +312,13 @@ def post(self):
attempts = 0
while attempts < 100:
try:
conn.execute(sql, {"user": username, "data": datastr, "key": hexdigest, "date": date, "description": description})
break
with db_engine.begin() as connection:
connection.execute(sql, {"user": username, "data": datastr, "key": hexdigest, "date": date, "description": description})
break
except:
pass
hexdigest = hashlib.sha224((datastr + str(random.random())).encode('utf-8')).hexdigest()[0:9]
attempts += 1

conn.commit()
conn.close()

return jsonify({"success": attempts < 100})

Expand All @@ -333,14 +331,15 @@ def get(self, key):
if not username:
return jsonify({"success": False})

conn, permalinks_table, user_permalink_table, user_bookmark_table = db_conn()
db_engine, permalinks_table, user_permalink_table, user_bookmark_table = db_conn()
sql = sql_text("""
SELECT data
FROM {table}
WHERE username = :user and key = :key
""".format(table=user_bookmark_table))
try:
data = json.loads(conn.execute(sql, {"user": username, "key": key}).mappings().first()["data"])
with db_engine.connect() as connection:
data = json.loads(connection.execute(sql, {"user": username, "key": key}).mappings().first()["data"])
except:
data = {}
return jsonify(data)
Expand All @@ -353,15 +352,14 @@ def delete(self, key):
return jsonify({"success": False})

# Delete into databse
conn, permalinks_table, user_permalink_table, user_bookmark_table = db_conn()
db_engine, permalinks_table, user_permalink_table, user_bookmark_table = db_conn()
sql = sql_text("""
DELETE FROM {table}
WHERE key = :key and username = :username
""".format(table=user_bookmark_table))

conn.execute(sql, {"key": key, "username": username})
conn.commit()
conn.close()
with db_engine.begin() as connection:
connection.execute(sql, {"key": key, "username": username})

return jsonify({"success": True})

Expand Down Expand Up @@ -395,7 +393,7 @@ def put(self, key):
}

# Update into databse
conn, permalinks_table, user_permalink_table, user_bookmark_table = db_conn()
db_engine, permalinks_table, user_permalink_table, user_bookmark_table = db_conn()
datastr = json.dumps(data)
date = datetime.date.today().strftime(r"%Y-%m-%d")

Expand All @@ -406,9 +404,8 @@ def put(self, key):
WHERE username = :user and key = :key
""".format(table=user_bookmark_table))

conn.execute(sql, {"user": username, "data": datastr, "key": key, "date": date, "description": description})
conn.commit()
conn.close()
with db_engine.begin() as connection:
connection.execute(sql, {"user": username, "data": datastr, "key": key, "date": date, "description": description})

return jsonify({"success": True})

Expand All @@ -422,7 +419,9 @@ def ready():
@app.route("/healthz", methods=['GET'])
def healthz():
try:
db_conn()
db_engine, permalinks_table, user_permalink_table, user_bookmark_table = db_conn()
with db_engine.connect() as connection:
connection.execute(sql_text("SELECT 1"))
except Exception as e:
return make_response(jsonify(
{"status": "FAIL", "cause":
Expand Down

0 comments on commit 4ce683c

Please sign in to comment.