-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
51 lines (39 loc) · 1.45 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
import json
from flask import Flask
import psycopg2
import os
app = Flask(__name__)
if 'POSTGRES_PASSWORD_FILE' in os.environ:
with open(os.environ['POSTGRES_PASSWORD_FILE'], 'r') as f:
password = f.read().strip()
else:
password = os.environ['POSTGRES_PASSWORD']
@app.route('/')
def hello_world():
return 'Hello, Dockers!!!'
@app.route('/widgets')
def get_widgets():
with psycopg2.connect(host="db", user="postgres", password=password, database="example") as conn:
with conn.cursor() as cur:
cur.execute("SELECT * FROM widgets")
row_headers = [x[0] for x in cur.description]
results = cur.fetchall()
conn.close()
json_data = [dict(zip(row_headers, result)) for result in results]
return json.dumps(json_data)
@app.route('/initdb')
def db_init():
conn = psycopg2.connect(host="db", user="postgres", password=password)
conn.set_session(autocommit=True)
with conn.cursor() as cur:
cur.execute("DROP DATABASE IF EXISTS example")
cur.execute("CREATE DATABASE example")
conn.close()
with psycopg2.connect(host="db", user="postgres", password=password, database="example") as conn:
with conn.cursor() as cur:
cur.execute("DROP TABLE IF EXISTS widgets")
cur.execute("CREATE TABLE widgets (name VARCHAR(255), description VARCHAR(255))")
conn.close()
return 'init database'
if __name__ == "__main__":
app.run(host='0.0.0.0')