Advertisement
Guest User

Untitled

a guest
Aug 9th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.61 KB | None | 0 0
  1. from flask import Flask
  2. from flask import render_template
  3. from flask import request
  4.  
  5. import os
  6. from urllib.parse import urlparse
  7. import json
  8.  
  9. import psycopg2
  10. from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
  11.  
  12. app = Flask(__name__)
  13.  
  14. # connection string and db connection initialization
  15. POSTGRESQL_URL = os.environ['POSTGRESQL_URL']
  16. parsed = urlparse(POSTGRESQL_URL)
  17.  
  18. # Open a connection to the default compose database
  19. conn = psycopg2.connect(
  20. host=parsed.hostname,
  21. port=parsed.port,
  22. user=parsed.username,
  23. password=parsed.password,
  24. database='compose')
  25.  
  26. # Now query it to see if the "grand_tour" database exists
  27. cursor=conn.cursor()
  28. cursor.execute("SELECT COUNT(*) = 0 FROM pg_catalog.pg_database WHERE datname = 'grand_tour'")
  29. not_exists_row = cursor.fetchone()
  30. not_exists = not_exists_row[0]
  31. if not_exists:
  32. # It doesn't. We get to create it here.
  33. # We have to tweak the isolation level so we aren't in a transaction
  34. conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
  35. # Now we get our cursor again
  36. cursor=conn.cursor()
  37. # And we create the database
  38. cursor.execute('CREATE DATABASE grand_tour')
  39.  
  40. # Whatever happened previously, now we can open a connection to the
  41. # "grand_tour" database and carry on...
  42.  
  43. conn = psycopg2.connect(
  44. host=parsed.hostname,
  45. port=parsed.port,
  46. user=parsed.username,
  47. password=parsed.password,
  48. database='grand_tour')
  49.  
  50. @app.route('/')
  51. # top-level page display, creates table if it doesn't exist
  52. def serve_page(name=None):
  53. cur = conn.cursor()
  54. cur.execute("""CREATE TABLE IF NOT EXISTS words (
  55. id serial primary key,
  56. word varchar(256) NOT NULL,
  57. definition varchar(256) NOT NULL) """)
  58. return render_template('index.html', name=name)
  59.  
  60. @app.route('/words', methods=['PUT'])
  61. # triggers on hitting the 'Add' button; inserts word/definition into table
  62. def handle_words(name=None):
  63. cur = conn.cursor()
  64. cur.execute("""INSERT INTO words (word, definition)
  65. VALUES (%s, %s)""",(request.form['word'],request.form['definition']))
  66. conn.commit()
  67. return "ECHO: PUT\n"
  68.  
  69. @app.route('/words', methods=['GET'])
  70. # query for all the rows in the table,\
  71. # makes a dictionary object from the column names and the results,\
  72. # makes json from the dict for display on the page.
  73. def display_find(name=None):
  74. cur = conn.cursor()
  75. cur.execute("""SELECT word, definition FROM words""")
  76. cursor_obj = cur.fetchall()
  77.  
  78. labels = [column[0] for column in cur.description]
  79. results_list = []
  80.  
  81. for row in cursor_obj:
  82. results_list.append(dict(zip(labels, row)))
  83.  
  84. return json.dumps(results_list)
  85.  
  86. if __name__ == "__main__":
  87. app.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement