Skip to content

Instantly share code, notes, and snippets.

@tuner
Created June 19, 2017 16:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tuner/cd2ebb532c570f5156267fdb7fd28422 to your computer and use it in GitHub Desktop.
Save tuner/cd2ebb532c570f5156267fdb7fd28422 to your computer and use it in GitHub Desktop.
sqlite & flask test
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)
<!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