Added UnixTimestamp type to Marshmallow Schemas

Added marshmallow to requirements.txt. Removed comments from app.py. Added UnixTimestamp type to schema.py
master
androiddrew 8 years ago
parent eaf1125279
commit 74def7032c

@ -55,7 +55,6 @@ def get_source(session: Session, id: int):
def get_articles(session: Session):
articles = session.query(NewsArticle).all()
# return [article.to_dict() for article in articles]
return http.Response(news_article_schema.dump(articles, many=True).data, status=200)

@ -4,16 +4,41 @@ from marshmallow import Schema, fields
class PassDateTime(fields.DateTime):
"""Used to Pass Datetime deserialization """
def _deserialize(self, value, attr, data):
if isinstance(value, dt.datetime):
return value
return super()._deserialize(value, attr, data)
# TODO Write a better doc you fool
class UnixTimestamp(fields.DateTime):
"""A datetime unix timesstamp in UTC.
Example: ``1513906064.678202``
FIX THIS PART
Timezone-naive `datetime` objects are converted to
UTC (+00:00) by :meth:`Schema.dump <marshmallow.Schema.dump>`.
:meth:`Schema.load <marshmallow.Schema.load>` returns `datetime`
objects that are timezone-aware.
:param str format: Either ``"rfc"`` (for RFC822), ``"iso"`` (for ISO8601),
or a date format string. If `None`, defaults to "iso".
:param kwargs: The same keyword arguments that :class:`Field` receives.
"""
def _serialize(self, value, attr, obj):
if value is None:
return None
return value.timestamp()
class NewsSourceSchema(Schema):
id = fields.Int(dump_only=True)
created_date = fields.DateTime(dump_only=True)
modified_date = fields.DateTime(dump_only=True)
created_date = UnixTimestamp(dump_only=True)
modified_date = UnixTimestamp(dump_only=True)
url = fields.URL()
source_name = fields.Str(required=True, error_messages={'required': 'NewsSource name is a required field'})
source_type = fields.Str(required=True, error_messages={'required': 'NewsSource type is a required field'})
@ -23,11 +48,11 @@ class NewsSourceSchema(Schema):
class Meta:
ordered = True
# TODO deserialization of timestamp to
class NewsArticleSchema(Schema):
id = fields.Int(dump_only=True)
created_date = fields.DateTime(dump_only=True)
modified_date = fields.DateTime(dump_only=True)
created_date = UnixTimestamp(dump_only=True)
modified_date = UnixTimestamp(dump_only=True)
news_source_id = fields.Int(required=True, error_messages={
'required': 'A NewsArticle must include a NewsSource identified by NewsSource.id'}
)

@ -8,6 +8,7 @@ idna==2.6
itypes==1.1.0
Jinja2==2.9.6
MarkupSafe==1.0
marshmallow==2.15.0
psycopg2==2.7.3.2
py==1.4.34
pytest==3.2.3

Loading…
Cancel
Save