Skip to content
Myr

Documentation: Clarify instructions about changing row_factory for SQLite3 (#1573)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Clarify instructions about changing row_factory When I was working through the tutorial, this was very confusing to me; so, I've added the code and clarification that would have helped me get through it faster. * Clarify the nature of Row objects * Rewrite code example for further clarity.

authored by Leo Tindall · committed by Jeff Widman · parent c80ea94 · Browse files · 1 file+19 added−2 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+19 added−2 removed

  • other:+19 added−2 removed

1 file+19 added−2 removed

modified:docs/patterns/sqlite3.rst+19 added-2 removed
69 unmodified lines
70Now in each request handling function you can access `g.db` to get the71current open database connection. To simplify working with SQLite, a72row factory function is useful. It is executed for every result returned73from the database to convert the result. For instance, in order to get74dictionaries instead of tuples, this could be inserted into ``get_db``::74dictionaries instead of tuples, this could be inserted into the ``get_db`` 75function we created above::7677 def make_dicts(cursor, row):78 return dict((cursor.description[idx][0], value)79 for idx, value in enumerate(row))8081 db.row_factory = make_dicts8282Or even simpler::83This will make the sqlite3 module return dicts for this database connection, which are much nicer to deal with. Even more simply, we could place this in ``get_db`` instead::8485 db.row_factory = sqlite3.Row8687This would use Row objects rather than dicts to return the results of queries. These are ``namedtuple`` s, so we can access them either by index or by key. For example, assuming we have a ``sqlite3.Row`` called ``r`` for the rows ``id``, ``FirstName``, ``LastName``, and ``MiddleInitial``::8889 >>> # You can get values based on the row's name90 >>> r['FirstName']91 John92 >>> # Or, you can get them based on index93 >>> r[1]94 John95 # Row objects are also iterable:96 >>> for value in r:97 ... print(value)98 199 John100 Doe101 M102103Additionally, it is a good idea to provide a query function that combines104getting the cursor, executing and fetching the results::105 106 def query_db(query, args=(), one=False):
48 unmodified lines