Created
June 19, 2017 16:48
-
-
Save tuner/cd2ebb532c570f5156267fdb7fd28422 to your computer and use it in GitHub Desktop.
sqlite & flask test
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
from flask import Flask, g, render_template | |
import sqlite3 | |
import html | |
app = Flask(__name__) | |
def get_db(): | |
"""Opens a new database connection if there is none yet for the | |
current application context. | |
""" | |
if not hasattr(g, 'sqlite_db'): | |
g.sqlite_db = sqlite3.connect("test.db") | |
return g.sqlite_db | |
@app.teardown_appcontext | |
def close_db(error): | |
"""Closes the database again at the end of the request.""" | |
if hasattr(g, 'sqlite_db'): | |
g.sqlite_db.close() | |
@app.route('/') | |
def main(): | |
conn = get_db() | |
c = conn.cursor() | |
res = c.execute("SELECT * FROM test") | |
table_rows = "".join(["<tr>" + "".join(["<td>" + html.escape(str(x)) + "</td>" for x in row]) + "</tr>" | |
for row in res]) | |
return render_template("template.html", table_rows=table_rows) | |
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Diibadaa</title> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
</head> | |
<body> | |
<h1>Diibadaa</h1> | |
<table class="table"> | |
<tbody> | |
{{ table_rows|safe }} | |
</tbody> | |
</table> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment