Guest User

Untitled

a guest
Apr 18th, 2016
30
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.26 KB | None | 0 0
  1. import psycopg2
  2. import psycopg2.extras
  3. from flask import Flask, render_template, request
  4.  
  5. app = Flask(__name__)
  6.  
  7. def getConn():
  8.     #function to retrieve the password, construct
  9.     #the connection string then make the connection and return it.
  10.     pwFile = open("pw.txt", "r")
  11.     pw = pwFile.read();
  12.     pwFile.close()
  13.     connStr = "host='localhost' dbname= 'DBcw' user='postgres' \
  14.     password = "+ pw
  15.     # FOR LAB MACHINES
  16.     # connStr = "host='cmpstudb-01.cmp.uea.ac.uk' \
  17.     #          dbname= 'DBcw' user='yfs15buu' password = " + pw
  18.     conn=psycopg2.connect(connStr)          
  19.     return conn
  20.    
  21. @app.route('/')
  22. def home():
  23.     return render_template('home.html')
  24.  
  25. @app.route('/displaycat', methods =['GET'])
  26. def displayCat():
  27.     conn= None
  28.     try:
  29.         conn=getConn()
  30.         cur = conn.cursor()
  31.         cur.execute('SET search_path to public')
  32.        
  33.         cur.execute('SELECT * FROM category')
  34.         colNames = [desc[0] for desc in cur.description]
  35.         cate = cur.fetchall()
  36.         return render_template('showCategory.html', cate = cate, \
  37.                                 colNames = colNames)
  38.        
  39.     except Exception as e:
  40.         return render_template('home.html', msg = 'An error occured', error = e)
  41.        
  42.     finally:
  43.         if conn:
  44.             conn.close()
  45.    
  46. if __name__ == "__main__":
  47.         app.run(debug = True)
Add Comment
Please, Sign In to add comment