Skip to content

Commit

Permalink
Merge pull request #17 from drahamim/10-db-connections-leak
Browse files Browse the repository at this point in the history
10-db-connections-leak
  • Loading branch information
drahamim authored Jan 5, 2023
2 parents 7bffbb2 + 5020f34 commit 3318ce2
Show file tree
Hide file tree
Showing 5 changed files with 68 additions and 54 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -111,4 +111,4 @@ database.db

.DS_Store

config.toml
config.py
1 change: 1 addition & 0 deletions example.config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
SECRET_KEY = "<SOME TEXT HERER>"
9 changes: 0 additions & 9 deletions example.config.toml

This file was deleted.

2 changes: 1 addition & 1 deletion sql_commands
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
sqlite3 database.db
sqlite> .mode csv
sqlite> .import ./test_data/convertcsv.csv
sqlite> .import ./test_data/convertcsv.csv staffs
sqlite> SELECT * from staffs;
108 changes: 65 additions & 43 deletions src/invenflask/app.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
from flask import Flask
from flask import render_template, request, url_for, flash, redirect, abort
from flask import render_template, request, url_for, flash, redirect, abort, g
from pathlib import Path
import sqlite3
import toml


config_path = Path.cwd().joinpath('config.toml')

config_path = Path.cwd().joinpath('config.py')

app = Flask(__name__)
app.config.from_file(str(config_path), load=toml.load)
app.config.from_pyfile(config_path)
print(config_path)

print(app.config)


def get_db_connection():
Expand All @@ -18,15 +19,32 @@ def get_db_connection():
return conn


def get_db():
"""Opens a new database connection if there is none yet for the
current application context.
"""
if not hasattr(g, 'sqlite_db'):
g.sqlite_db = get_db_connection()
return g.sqlite_db


@app.teardown_appcontext
def close_db(error):
"""Closes the database again at the end of the request."""
if hasattr(g, 'sqlite_db'):
g.sqlite_db.close()


def get_asset(asset_id, action):
conn = get_db_connection()
conn = get_db()
asset = conn.execute('SELECT * FROM assets WHERE id = ?',
(asset_id,)).fetchone()
conn.close()
(asset_id,)).fetchone
conn.commit()
if action == "edit":
if asset is None:
abort(404)
else:
print(asset)
return asset
if action == "create":
if asset:
Expand All @@ -35,24 +53,25 @@ def get_asset(asset_id, action):


def get_staff(staff_id):
conn = get_db_connection()
conn = get_db()
staff = conn.execute('SELECT * FROM staffs WHERE id = ?',
(staff_id,)).fetchone()
conn.close()
conn.commit()
return staff


def get_checkout(asset_id):
conn = get_db_connection()
conn = get_db()
asset = conn.execute('SELECT * FROM checkouts WHERE assetid = ?',
(asset_id,)).fetchone()
conn.close()
conn.commit()
return asset


@app.route('/')
def index():
conn = get_db_connection()

conn = get_db()
assets = conn.execute('SELECT * FROM assets').fetchall()
asset_total = conn.execute('SELECT COUNT(*) FROM assets').fetchone()[0]
asset_types = conn.execute(
Expand All @@ -61,7 +80,7 @@ def index():
asset_status = conn.execute(
'SELECT asset_status, COUNT(*) FROM assets GROUP BY asset_status'
).fetchall()
conn.close()
conn.commit()
return render_template(
'index.html', assets=assets, asset_total=asset_total,
asset_type=asset_types, asset_status=asset_status)
Expand All @@ -80,13 +99,12 @@ def create_asset():
flash('Asset Type required')
else:
try:
conn = get_db_connection()
conn = get_db()
conn.execute(
'INSERT INTO assets (id, asset_type, asset_status)'
'VALUES (?, ?, ?)',
(id, asset_type, asset_status))
conn.commit()
conn.close()
return redirect(url_for('status'))
except sqlite3.IntegrityError:
flash("Asset already exists")
Expand All @@ -97,9 +115,9 @@ def create_asset():

@app.route('/status')
def status():
conn = get_db_connection()
conn = get_db()
assets = conn.execute('SELECT * FROM assets').fetchall()
conn.close()
conn.commit()
return render_template('status.html', assets=assets)


Expand All @@ -110,11 +128,10 @@ def edit_asset(id):
if request.method == 'POST':
asset_type = request.form['asset_type']
asset_status = request.form['asset_status']
conn = get_db_connection()
conn = get_db()
conn.execute('UPDATE assets SET asset_type = ?, asset_status = ?'
' WHERE id = ?', (asset_type, asset_status, id))
conn.commit()
conn.close()
return redirect(url_for('status'))

return render_template('edit_asset.html', asset=asset)
Expand All @@ -123,21 +140,20 @@ def edit_asset(id):
@app.route('/delete/<id>/', methods=('POST',))
def delete(id):
asset = get_asset(id, "edit")
conn = get_db_connection()
conn = get_db()
conn.execute('DELETE FROM assets WHERE id = ?', (asset,))
conn.commit()
conn.close()
flash('Asset "{}" was successfully deleted!'.format(id))
return redirect(url_for('index'))


@app.route('/staff/', methods=('GET', 'POST'))
def staff():
conn = get_db_connection()
conn = get_db()
if request.method == 'POST':
pass
staff = conn.execute('SELECT * FROM staffs').fetchall()
conn.close()
conn.commit()
return render_template('staff.html', staffs=staff)


Expand All @@ -147,7 +163,6 @@ def checkout():
asset_id = request.form['id']
accessory_id = request.form['accessoryid']
staff_id = request.form['staffid']

if not asset_id:
flash('Asset ID is required')
elif not staff_id:
Expand All @@ -158,14 +173,18 @@ def checkout():
elif get_asset(asset_id, 'edit') is False:
flash("Asset does not exist. Please make it below")
return redirect(url_for('create_asset'))
elif get_asset(asset_id, 'edit')['asset_status'] == 'damaged':
flash("Asset should not be checked out. Please choose another one")
return redirect(url_for('checkout'))
elif get_asset(asset_id, 'edit') is dict:
if get_asset(asset_id, 'edit')['asset_status'] == 'damaged':
flash("Asset should not be checked out. Please choose another one")
return redirect(url_for('checkout'))
else:
flash(
f"Something went wrong with {get_asset(asset_id, 'edit')}")
else:
staff_dept = get_staff(staff_id)['Department']
flash(get_asset(asset_id, 'edit')['asset_status'])
# flash(get_asset(asset_id, 'edit'))
try:
conn = get_db_connection()
conn = get_db()
conn.execute(
'INSERT INTO checkouts (assetid, staffid, department) '
'VALUES (?, ?, ?)', (asset_id, staff_id, staff_dept))
Expand All @@ -182,7 +201,6 @@ def checkout():
(accessory_id,))

conn.commit()
conn.close()
flash('Asset Checkout Completed')
return redirect(url_for('checkout'))
except sqlite3.IntegrityError:
Expand All @@ -202,28 +220,32 @@ def checkin():
elif get_asset(asset_id, "edit") is False:
flash("Asset does not exist. Please make it below")
return redirect(url_for('create_asset'))
elif get_checkout(asset_id) is None:
flash("Asset Not checked out")
return redirect(url_for('checkin'))
else:
asset_checkout = get_checkout(asset_id)
print(asset_checkout)
staff_div = get_staff(asset_checkout['staffid'])['Division']
try:
conn = get_db_connection()
conn = get_db()
conn.execute(
'INSERT INTO history (assetid, staffid, department, division, checkouttime) VALUES (?,?,?,?,?)',
(asset_id, asset_checkout['staffid'],
asset_checkout['department'], staff_div,
asset_checkout['timestamp']))
conn.execute(
'DELETE from checkouts WHERE assetid = ?', (asset_id,))
if get_asset(asset_id, "edit")['asset_status'] == "damaged":
conn.execute(
'UPDATE assets SET asset_status = ? WHERE id = ?',
('damaged', asset_id))
else:
conn.execute(
'UPDATE assets SET asset_status = ? WHERE id = ?',
('Available', asset_id))
if get_asset(asset_id, 'edit') is dict:
if get_asset(asset_id, "edit")['asset_status'] == "damaged":
conn.execute(
'UPDATE assets SET asset_status = ? WHERE id = ?',
('damaged', asset_id))
else:
conn.execute(
'UPDATE assets SET asset_status = ? WHERE id = ?',
('Available', asset_id))
conn.commit()
conn.close()
flash('Asset checkin Completed')
return redirect(url_for('checkout'))
except sqlite3.IntegrityError as e:
Expand All @@ -234,7 +256,7 @@ def checkin():

@app.route('/history')
def history():
conn = get_db_connection()
conn = get_db()
assets = conn.execute('SELECT * FROM history').fetchall()
conn.close()
conn.commit()
return render_template('history.html', assets=assets)

0 comments on commit 3318ce2

Please sign in to comment.