-
Notifications
You must be signed in to change notification settings - Fork 0
/
demo.py
48 lines (36 loc) · 1.26 KB
/
demo.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
import os
from flask import Flask, render_template, request
from psycopg2 import connect, Error
ALLOWED_EXTENSIONS = {"csv"}
app = Flask(__name__)
@app.route("/", methods=["GET", "POST"])
def home():
if request.method == "GET":
return render_template("base.html")
# get the form data
run_text = request.form["query"]
try:
# Connect to an existing database
connection = connect(
user="postgres", password="docker", host="demodb", port="5432", database="postgres"
)
# Create a cursor to perform database operations
cursor = connection.cursor()
# Executing a SQL query
cursor.execute(run_text)
col_names = (desc[0] for desc in cursor.description)
records = cursor.fetchmany(10)
records.insert(0, col_names)
except (Exception, Error) as error:
records = [("ERROR", error)]
print(records)
finally:
# print(connection)
if connection:
cursor.close()
connection.close()
# print("PostgreSQL connection is closed")
return render_template("results.html", records=records)
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5050))
app.run(debug=True, host="0.0.0.0", port=port)