-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.py
45 lines (37 loc) · 1.11 KB
/
db.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
from flask import current_app, g
import psycopg2
import os
import re
import urllib.parse
# def get_db():
# if "db" not in g:
# hostname = 'localhost'
# username = 'postgres'
# password = 'Porsche911'
# database = 'youtuber'
# conn = psycopg2.connect(
# host=hostname, user=username, password=password, dbname=database)
# conn.autocommit = True
# g.db = conn.cursor()
# return g.db
def get_db():
if "db" not in g:
DATABASE_URI = os.getenv("DATABASE_URI")
parsed_uri = urllib.parse.urlparse(DATABASE_URI)
username = parsed_uri.username
password = parsed_uri.password
host = parsed_uri.hostname
port = parsed_uri.port
database = parsed_uri.path[1:]
conn = psycopg2.connect(
host=host, user=username, password=password, dbname=database, port=port
)
conn.autocommit = True
g.db = conn.cursor()
return g.db
def close_db(e=None):
db = g.pop("db", None)
if db is not None:
db.close()
def init_app(app):
app.teardown_appcontext(close_db)