From 10adc158856ef1c2452de41956b0c9ee40488a4e Mon Sep 17 00:00:00 2001 From: assar Date: Thu, 1 Jun 2017 22:30:19 +0000 Subject: [PATCH] Added function to connect to database --- server.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/server.py b/server.py index 27d2472..511ddac 100644 --- a/server.py +++ b/server.py @@ -1,9 +1,32 @@ +import json import sqlalchemy from flask import Flask from flask import render_template app = Flask(__name__) +db_engine = {} +db_metadata = {} + @app.route('/') def index(): return render_template('partsearch.html') + +def connect(user, password, db, host='localhost', port=5432): + '''Returns a connection and a metadata object''' + # We connect with the help of the PostgreSQL URL + url = 'postgresql://{}:{}@{}:{}/{}' + url = url.format(user, password, host, port, db) + + # The return value of create_engine() is our connection object + con = sqlalchemy.create_engine(url, client_encoding='utf8') + + # We then bind the connection to MetaData() + meta = sqlalchemy.MetaData(bind=con, reflect=True) + + return con, meta + +if __name__ == '__main__': + with open('admin.json') as f: + postgres_credentials = json.load(f) + db_engine, db_metadata = connect(postgres_credentials['username'], postgres_credentials['password'], 'parts')