Last active
March 19, 2020 13:40
-
-
Save bourque/8574b64e1129d3e3c1655c6126c5dc97 to your computer and use it in GitHub Desktop.
A simple demo of a Flask web app that queries a sqlite database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<p> This is the database page </p> | |
{% for state, capital in results_dict.items() %} | |
<p> {{state}}: {{capital}} </p> | |
{% endfor %} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
BEGIN; | |
CREATE TABLE main_table ( | |
"id" INTEGER NOT NULL PRIMARY KEY, | |
"state" TEXT NOT NULL UNIQUE, | |
"capital" TEXT | |
); | |
INSERT INTO main_table (state, capital) VALUES ("Massachusetts", "Boston"); | |
INSERT INTO main_table (state, capital) VALUES ("Indiana", "Indianapolis"); | |
INSERT INTO main_table (state, capital) VALUES ("Maryland", "Annapolis"); | |
INSERT INTO main_table (state, capital) VALUES ("New York", "Albany"); | |
INSERT INTO main_table (state, capital) VALUES ("Texas", "Austin"); | |
COMMIT; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<p> This is the homepage </p> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env python | |
from flask import Flask, render_template | |
import sqlite3 | |
app = Flask(__name__) | |
@app.route('/database/') | |
def database(): | |
"""Returns webpage containing query results from database | |
Returns | |
------- | |
template : obj | |
The ``database.html`` webpage. | |
""" | |
# Connect to database | |
connection = sqlite3.connect('data.db') | |
cursor = connection.cursor() | |
# Execute query | |
sql_command = 'SELECT * FROM main_table;' | |
cursor.execute(sql_command) | |
# Parse results | |
results_dict = {} | |
results = cursor.fetchall() | |
for result in results: | |
results_dict[result[1]] = result[2] | |
return render_template('database.html', results_dict=results_dict) | |
@app.route('/') | |
def main(): | |
"""Generates the website homepage. | |
Returns | |
------- | |
template : obj | |
The ``index.html`` template. | |
""" | |
return render_template('index.html') | |
if __name__ == '__main__': | |
app.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment