Skip to content
Myr

add sqlite datetime converter

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

authored by David Lord · committed by David Lord · parent df201ed · Browse files · 2 files+14 added−0 removed
This commit

State

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

Diff stats

2 files+14 added−0 removed

  • other:+14 added−0 removed

2 files+14 added−0 removed

modified:docs/tutorial/database.rst+10 added
35 unmodified lines
36.. code-block:: python37 :caption: ``flaskr/db.py``3839 import sqlite340 from datetime import datetime4142 import click43 from flask import current_app, g44
87 unmodified lines
132 """Clear the existing data and create new tables."""133 init_db()134 click.echo('Initialized the database.')135136137 sqlite3.register_converter(138 "timestamp", lambda v: datetime.fromisoformat(v.decode())139 )140141:meth:`open_resource() <Flask.open_resource>` opens a file relative to142the ``flaskr`` package, which is useful since you won't necessarily know143where that location is when deploying the application later. ``get_db``144returns a database connection, which is used to execute the commands
2 unmodified lines
147:func:`click.command` defines a command line command called ``init-db``148that calls the ``init_db`` function and shows a success message to the149user. You can read :doc:`/cli` to learn more about writing commands.150151The call to :func:`sqlite3.register_converter` tells Python how to152interpret timestamp values in the database. We convert the value to a153:class:`datetime.datetime`.154155156Register with the Application157-----------------------------158159The ``close_db`` and ``init_db_command`` functions need to be registered
60 unmodified lines
modified:examples/tutorial/flaskr/db.py+4 added
1import sqlite32from datetime import datetime34import click5from flask import current_app6from flask import g
37 unmodified lines
44 init_db()45 click.echo("Initialized the database.")464748sqlite3.register_converter("timestamp", lambda v: datetime.fromisoformat(v.decode()))495051def init_app(app):52 """Register database functions with the Flask app. This is called by53 the application factory.54 """
2 unmodified lines