-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
52 lines (40 loc) · 1.62 KB
/
Copy pathapp.py
File metadata and controls
52 lines (40 loc) · 1.62 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
from flask import Flask, jsonify, abort
import psycopg2
app = Flask(__name__)
@app.route('/')
def empty_homepage():
return ''
@app.route('/users', methods=['GET'])
def get_users():
with psycopg2.connect(dbname='postgres', user='postgres', password='postgres',
host='db', port=5432) as conn:
with conn.cursor() as cursor:
cursor.execute('SELECT * FROM users')
users = cursor.fetchall()
if len(users) == 0:
abort(404)
return jsonify({'users': users})
@app.route('/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
with psycopg2.connect(dbname='postgres', user='postgres', password='postgres',
host='db', port=5432) as conn:
with conn.cursor() as cursor:
cursor.execute('SELECT * FROM users WHERE id = %s', (user_id, ))
users = cursor.fetchall()
if len(users) == 0:
abort(404)
return jsonify({'user': users[0]})
@app.route('/users/<int:user_id>', methods=['DELETE'])
def delete_user(user_id):
with psycopg2.connect(dbname='postgres', user='postgres', password='postgres',
host='db', port=5432) as conn:
with conn.cursor() as cursor:
cursor.execute('SELECT * FROM users WHERE id = %s', (user_id, ))
users = cursor.fetchall()
if len(users) == 0:
abort(404)
else:
cursor.execute('DELETE FROM users WHERE id = %s', (user_id, ))
return jsonify({'result': True})
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')