-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpartdb.py
More file actions
76 lines (53 loc) · 1.76 KB
/
partdb.py
File metadata and controls
76 lines (53 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# all the imports. ALL OF THEM
import os
import sqlite3
from flask import Flask, g, render_template, jsonify, request, abort
# create our app
app = Flask(__name__)
# set up default config
app.config.update(dict(
DATABASE=os.path.join(app.root_path, 'partdb.db')
))
app.config.from_envvar('PARTSDB_SETTINGS', silent=True)
def connect_db():
rv = sqlite3.connect(app.config['DATABASE'])
rv.row_factory = sqlite3.Row
return rv
def get_db():
if not hasattr(g, 'db'):
g.db = connect_db()
return g.db
@app.teardown_appcontext
def close_db(err):
if hasattr(g, 'db'):
g.db.close()
def init_db():
db = get_db()
with app.open_resource('schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
with app.open_resource('data.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()
def clean_name(some_var):
return ''.join(char for char in some_var if char.isalnum())
@app.cli.command('initdb')
def initialize_db_cmd():
init_db()
print("Initialized the database")
@app.route('/')
def index_query():
return render_template('iquery.html')
@app.route('/parts/query')
def part_query():
search_field = request.args.get('field')
search_query = request.args.get('query')
db = get_db()
if search_field not in ['drawer', 'category', 'partnum', 'description']:
abort(400, "Invalid query field.")
SEL = 'SELECT drawer, category, partnum, description FROM parts'
if search_field == 'drawer':
parts = db.execute(f'{SEL} WHERE drawer = ?', (search_query,))
else:
parts = db.execute(f'{SEL} WHERE instr({search_field}, ?)',
(search_query,)).fetchall()
return render_template('query_results.html', results=parts)