-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
99 lines (81 loc) · 2.67 KB
/
app.py
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
from flask import Flask, render_template, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
import yaml
app = Flask(__name__)
db_config = yaml.load(open('database.yaml')) #URL to open database
app.config['SQLALCHEMY_DATABASE_URI'] = db_config['uri']
db = SQLAlchemy(app)
CORS(app)
class User(db.Model):
__tablename__ = "tablename"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255))
age = db.Column(db.String(255))
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return '%s/%s/%s' % (self.id, self.name, self.age)
@app.route('/')
def index():
return render_template('home.html')
@app.route('/data', methods=['POST', 'GET'])
def data():
# POST a data to database
if request.method == 'POST':
body = request.json
name = body['name']
age = body['age']
data = User(name, age)
db.session.add(data)
db.session.commit()
return jsonify({
'status': 'Data has been posted to database!',
'name': name,
'age': age
})
# GET all data from database & sort by id
if request.method == 'GET':
data = User.query.order_by(User.id).all()
print(data)
dataJson = []
for i in range(len(data)):
dataDict = {
'id': str(data[i]).split('/')[0],
'name': str(data[i]).split('/')[1],
'age': str(data[i]).split('/')[2]
}
dataJson.append(dataDict)
return jsonify(dataJson)
@app.route('/data/<string:id>', methods=['GET', 'DELETE', 'PUT'])
def onedata(id):
# GET a specific data by id
if request.method == 'GET':
data = User.query.get(id)
print(data)
dataDict = {
'id': str(data).split('/')[0],
'name': str(data).split('/')[1],
'age': str(data).split('/')[2]
}
return jsonify(dataDict)
# DELETE a data
if request.method == 'DELETE':
delData = User.query.filter_by(id=id).first()
db.session.delete(delData)
db.session.commit()
return jsonify({'status': 'Data ' + id + ' is deleted from PostgreSQL!'})
# UPDATE a data by id
if request.method == 'PUT':
body = request.json
newName = body['name']
newAge = body['age']
editData = User.query.filter_by(id=id).first()
editData.name = newName
editData.age = newAge
db.session.commit()
return jsonify({'status': 'Data ' + id + ' is updated from PostgreSQL!'})
if __name__ == '__main__':
app.debug = True
app.run()