Skip to content
This repository has been archived by the owner on Mar 24, 2021. It is now read-only.

Commit

Permalink
Backdrop read api should always return UTC
Browse files Browse the repository at this point in the history
Consumers of backdrop will always want datetimes to be represented as
UTC. Previously they had no timezone attached, which was rather confusing
as the ISODate in mongo had a timezone.

This commit will force all datetime objects coming out of backdrop into
UTC before writing them out to JSON.
  • Loading branch information
tombooth committed Apr 29, 2014
1 parent 269817a commit 5655e44
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
3 changes: 2 additions & 1 deletion backdrop/read/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from ..core.data_set import DataSet
from ..core.database import InvalidOperationError
from ..core.repository import DataSetConfigRepository
from ..core.timeutils import as_utc


GOVUK_ENV = getenv("GOVUK_ENV", "development")
Expand Down Expand Up @@ -43,7 +44,7 @@ def default(self, obj):
if isinstance(obj, ObjectId):
return str(obj)
if isinstance(obj, datetime.datetime):
return obj.isoformat()
return as_utc(obj).isoformat()
return json.JSONEncoder.default(self, obj)
app.json_encoder = JsonEncoder

Expand Down
28 changes: 28 additions & 0 deletions tests/read/test_read_api_json_encoder.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import unittest
import pytz

from hamcrest import *
from datetime import datetime
from backdrop.read.api import JsonEncoder


class TestReadAPIJSONEcoder(unittest.TestCase):

def test_with_utc_date(self):
obj = {'date': datetime(2014, 4, 29, 1, 0, 0, 0, pytz.utc)}
assert_that(
JsonEncoder().encode(obj),
is_('{"date": "2014-04-29T01:00:00+00:00"}'))

def test_with_est_date(self):
est = pytz.timezone('US/Eastern')
obj = {'date': datetime(2014, 4, 29, 1, 0, 0, 0, est)}
assert_that(
JsonEncoder().encode(obj),
is_('{"date": "2014-04-29T06:00:00+00:00"}'))

def test_with_no_tz_date(self):
obj = {'date': datetime(2014, 4, 29, 1, 0)}
assert_that(
JsonEncoder().encode(obj),
is_('{"date": "2014-04-29T01:00:00+00:00"}'))

0 comments on commit 5655e44

Please sign in to comment.