Skip to content
Snippets Groups Projects
Commit 89a3e0ef authored by Benjamin Bertrand's avatar Benjamin Bertrand
Browse files

Allow to pass created_at/updated_at fields as strings

Strings are automatically converted to datetime object.
Note that datetime are stored without timezone in the database (in UTC).
parent 3d9b8f3a
No related branches found
No related tags found
No related merge requests found
...@@ -262,6 +262,15 @@ class CreatedMixin: ...@@ -262,6 +262,15 @@ class CreatedMixin:
def user(cls): def user(cls):
return db.relationship('User') return db.relationship('User')
def __init__(self, **kwargs):
# Automatically convert created_at/updated_at strings
# to datetime object
for key in ('created_at', 'updated_at'):
if key in kwargs:
if isinstance(kwargs[key], str):
kwargs[key] = utils.parse_to_utc(kwargs[key])
super().__init__(**kwargs)
def to_dict(self): def to_dict(self):
return { return {
'id': self.id, 'id': self.id,
......
...@@ -13,6 +13,7 @@ import base64 ...@@ -13,6 +13,7 @@ import base64
import datetime import datetime
import io import io
import sqlalchemy as sa import sqlalchemy as sa
import dateutil.parser
from flask.globals import _app_ctx_stack, _request_ctx_stack from flask.globals import _app_ctx_stack, _request_ctx_stack
from flask_login import current_user from flask_login import current_user
from flask_jwt_extended import get_current_user from flask_jwt_extended import get_current_user
...@@ -168,3 +169,14 @@ def coerce_to_str_or_none(value): ...@@ -168,3 +169,14 @@ def coerce_to_str_or_none(value):
if not value or value == 'None': if not value or value == 'None':
return None return None
return str(value) return str(value)
def parse_to_utc(string):
"""Convert a string to a datetime object with no timezone"""
d = dateutil.parser.parse(string)
if d.tzinfo is None:
# Assume this is UTC
return d
# Convert to UTC and remove timezone
d = d.astimezone(datetime.timezone.utc)
return d.replace(tzinfo=None)
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment