forked from senyee18/TicketProject
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqlite-server.py
More file actions
100 lines (71 loc) · 2 KB
/
sqlite-server.py
File metadata and controls
100 lines (71 loc) · 2 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import sqlite3
from flask import Flask, jsonify, request, abort
from argparse import ArgumentParser
DB = 'bus.sqlite'
def get_row_as_dict(row):
row_dict = {
'id': row[0],
'price': row[1],
'departure': row[2],
'arrival': row[3],
'departureTime': row[4],
'date': row[5],
}
return row_dict
app = Flask(__name__)
@app.route('/api/bus', methods=['GET'])
def index():
db = sqlite3.connect(DB)
cursor = db.cursor()
cursor.execute('SELECT * FROM bus ORDER BY date')
rows = cursor.fetchall()
print(rows)
db.close()
rows_as_dict = []
for row in rows:
row_as_dict = get_row_as_dict(row)
rows_as_dict.append(row_as_dict)
return jsonify(rows_as_dict), 200
@app.route('/api/bus/<int:bus>', methods=['GET'])
def show(member):
db = sqlite3.connect(DB)
cursor = db.cursor()
cursor.execute('SELECT * FROM bus WHERE id=?', (str(bus),))
row = cursor.fetchone()
db.close()
if row:
row_as_dict = get_row_as_dict(row)
return jsonify(row_as_dict), 200
else:
return jsonify(None), 200
@app.route('/api/bus', methods=['POST'])
def store():
if not request.json:
abort(404)
new_bus = (
request.json['price'],
request.json['departure'],
request.json['arrival'],
request.json['departureTime'],
request.json['date'],
)
db = sqlite3.connect(DB)
cursor = db.cursor()
cursor.execute('''
INSERT INTO bus(price,departure,arrival,departureTime,date)
VALUES(?,?,?,?,?)
''', new_bus)
bus_id = cursor.lastrowid
db.commit()
response = {
'id': bus_id,
'affected': db.total_changes,
}
db.close()
return jsonify(response), 201
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument('-p', '--port', default=5000, type=int, help='port to listen on')
args = parser.parse_args()
port = args.port
app.run(host='0.0.0.0', port=port)