add sqlite datetime converter
This commit is contained in:
parent
df201ed152
commit
8aa161a437
2 changed files with 14 additions and 0 deletions
|
|
@ -37,6 +37,7 @@ response is sent.
|
||||||
:caption: ``flaskr/db.py``
|
:caption: ``flaskr/db.py``
|
||||||
|
|
||||||
import sqlite3
|
import sqlite3
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
import click
|
import click
|
||||||
from flask import current_app, g
|
from flask import current_app, g
|
||||||
|
|
@ -132,6 +133,11 @@ Add the Python functions that will run these SQL commands to the
|
||||||
init_db()
|
init_db()
|
||||||
click.echo('Initialized the database.')
|
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
|
:meth:`open_resource() <Flask.open_resource>` opens a file relative to
|
||||||
the ``flaskr`` package, which is useful since you won't necessarily know
|
the ``flaskr`` package, which is useful since you won't necessarily know
|
||||||
where that location is when deploying the application later. ``get_db``
|
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
|
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.
|
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
|
Register with the Application
|
||||||
-----------------------------
|
-----------------------------
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
import sqlite3
|
import sqlite3
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
import click
|
import click
|
||||||
from flask import current_app
|
from flask import current_app
|
||||||
|
|
@ -44,6 +45,9 @@ def init_db_command():
|
||||||
click.echo("Initialized the database.")
|
click.echo("Initialized the database.")
|
||||||
|
|
||||||
|
|
||||||
|
sqlite3.register_converter("timestamp", lambda v: datetime.fromisoformat(v.decode()))
|
||||||
|
|
||||||
|
|
||||||
def init_app(app):
|
def init_app(app):
|
||||||
"""Register database functions with the Flask app. This is called by
|
"""Register database functions with the Flask app. This is called by
|
||||||
the application factory.
|
the application factory.
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue