-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
72 lines (60 loc) 路 2.18 KB
/
Copy pathapi.py
File metadata and controls
72 lines (60 loc) 路 2.18 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
"""API to work with sqlite3 database"""
from flask import Flask, request, jsonify
import sqlite3
app = Flask(__name__)
def db_connection():
conn = None
try:
conn = sqlite3.connect("phone_brands.db")
except sqlite3.Error as e:
print("Error while connecting to SQLite database:", e)
return conn
@app.route(rule="/gsm_brands", methods=["GET"])
def gsm_brands():
conn = db_connection()
cursor = conn.cursor()
if request.method == "GET":
try:
get_brands = "SELECT * FROM brands;"
cursor.execute(get_brands)
brands = [
dict(id=row[0], brand=row[1], device_num=row[3])
for row in cursor.fetchall()
]
return jsonify(brands), 200
except sqlite3.Error as e:
return jsonify({"error": str(e)}), 500
@app.route(rule="/gsm_brands/<brand_name>", methods=["GET"])
def gsm_brand(brand_name):
conn = db_connection()
cursor = conn.cursor()
if request.method == "GET":
try:
get_devices = f"SELECT * FROM {brand_name}_devices;"
cursor.execute(get_devices)
devices = [
dict(id=row[0], brand=row[2], device_name=row[1])
for row in cursor.fetchall()
]
return jsonify(devices), 200
except sqlite3.Error as e:
return jsonify({"error": str(e)}), 500
@app.route(rule="/gsm_brands/<brand_name>/<device_name>", methods=["GET"])
def gsm_device(brand_name, device_name):
conn = db_connection()
cursor = conn.cursor()
if request.method == "GET":
try:
get_device = f"SELECT * FROM {brand_name}_{device_name};"
cursor.execute(get_device)
device_specs_headers = [
description[0] for description in cursor.description
]
device_specs = [
dict(zip(device_specs_headers, row)) for row in cursor.fetchall()
]
return jsonify(device_specs), 200
except sqlite3.Error as e:
return jsonify({"error": str(e)}), 500
if __name__ == "__main__":
app.run(debug=True) # Running the Flask application in debug mode.