add sqlite datetime converter

This commit is contained in:
David Lord 2024-11-01 17:18:52 -07:00
parent df201ed152
commit 8aa161a437
No known key found for this signature in database
GPG Key ID: 43368A7AA8CC5926
2 changed files with 14 additions and 0 deletions

View File

@ -37,6 +37,7 @@ response is sent.
:caption: ``flaskr/db.py``
import sqlite3
from datetime import datetime
import click
from flask import current_app, g
@ -132,6 +133,11 @@ Add the Python functions that will run these SQL commands to the
init_db()
click.echo('Initialized the database.')
sqlite3.register_converter(
"timestamp", lambda v: datetime.fromisoformat(v.decode())
)
:meth:`open_resource() <Flask.open_resource>` opens a file relative to
the ``flaskr`` package, which is useful since you won't necessarily know
where that location is when deploying the application later. ``get_db``
@ -142,6 +148,10 @@ read from the file.
that calls the ``init_db`` function and shows a success message to the
user. You can read :doc:`/cli` to learn more about writing commands.
The call to :func:`sqlite3.register_converter` tells Python how to
interpret timestamp values in the database. We convert the value to a
:class:`datetime.datetime`.
Register with the Application
-----------------------------

View File

@ -1,4 +1,5 @@
import sqlite3
from datetime import datetime
import click
from flask import current_app
@ -44,6 +45,9 @@ def init_db_command():
click.echo("Initialized the database.")
sqlite3.register_converter("timestamp", lambda v: datetime.fromisoformat(v.decode()))
def init_app(app):
"""Register database functions with the Flask app. This is called by
the application factory.