|
|
|
@ -3,8 +3,8 @@
|
|
|
|
|
Using SQLite 3 with Flask |
|
|
|
|
========================= |
|
|
|
|
|
|
|
|
|
In Flask you can easily implement the opening of database connections on |
|
|
|
|
demand and closing them when the context dies (usually at the end of the |
|
|
|
|
In Flask you can easily implement the opening of database connections on |
|
|
|
|
demand and closing them when the context dies (usually at the end of the |
|
|
|
|
request). |
|
|
|
|
|
|
|
|
|
Here is a simple example of how you can use SQLite 3 with Flask:: |
|
|
|
@ -71,7 +71,7 @@ Now in each request handling function you can access `g.db` to get the
|
|
|
|
|
current open database connection. To simplify working with SQLite, a |
|
|
|
|
row factory function is useful. It is executed for every result returned |
|
|
|
|
from the database to convert the result. For instance, in order to get |
|
|
|
|
dictionaries instead of tuples, this could be inserted into the ``get_db`` |
|
|
|
|
dictionaries instead of tuples, this could be inserted into the ``get_db`` |
|
|
|
|
function we created above:: |
|
|
|
|
|
|
|
|
|
def make_dicts(cursor, row): |
|
|
|
@ -102,15 +102,15 @@ This would use Row objects rather than dicts to return the results of queries. T
|
|
|
|
|
|
|
|
|
|
Additionally, it is a good idea to provide a query function that combines |
|
|
|
|
getting the cursor, executing and fetching the results:: |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def query_db(query, args=(), one=False): |
|
|
|
|
cur = get_db().execute(query, args) |
|
|
|
|
rv = cur.fetchall() |
|
|
|
|
cur.close() |
|
|
|
|
return (rv[0] if rv else None) if one else rv |
|
|
|
|
|
|
|
|
|
This handy little function, in combination with a row factory, makes |
|
|
|
|
working with the database much more pleasant than it is by just using the |
|
|
|
|
This handy little function, in combination with a row factory, makes |
|
|
|
|
working with the database much more pleasant than it is by just using the |
|
|
|
|
raw cursor and connection objects. |
|
|
|
|
|
|
|
|
|
Here is how you can use it:: |
|
|
|
@ -131,7 +131,7 @@ To pass variable parts to the SQL statement, use a question mark in the
|
|
|
|
|
statement and pass in the arguments as a list. Never directly add them to |
|
|
|
|
the SQL statement with string formatting because this makes it possible |
|
|
|
|
to attack the application using `SQL Injections |
|
|
|
|
<http://en.wikipedia.org/wiki/SQL_injection>`_. |
|
|
|
|
<https://en.wikipedia.org/wiki/SQL_injection>`_. |
|
|
|
|
|
|
|
|
|
Initial Schemas |
|
|
|
|
--------------- |
|
|
|
|