Flask-PyMongo always uses timezone-aware datetime objects. That is, it sets the tz_aware parameter to True when creating a connection. The timezone of datetime objects returned from MongoDB will always be UTC.
flask-session, on the other hand, compares the expires value in the document against datetime.utcnow() which is not time zone aware.
Then the above exception is thrown:
TypeError: can't compare offset-naive and offset-aware datetimes
The workaround (that works for me) is to replace this line:
if document and document.get('expiration') <= datetime.utcnow():
with these two lines:
import pytz
if document and document.get('expiration') <= datetime.utcnow().replace(tzinfo=pytz.UTC):
A permanent solution may be to examine self.client.codec_options.tz_aware (which is a boolean) and act accordingly.
I'm using
flask-session
with MongoDB (with the help ofFlask-PyMongo
).Flask-PyMongo
uses timezone-aware datetime objects.From its docs:
flask-session
, on the other hand, compares theexpires
value in the document againstdatetime.utcnow()
which is not time zone aware.Then the above exception is thrown:
TypeError: can't compare offset-naive and offset-aware datetimes
The workaround (that works for me) is to replace this line:
with these two lines:
A permanent solution may be to examine
self.client.codec_options.tz_aware
(which is a boolean) and act accordingly.flask == 0.12.2 Flask-PyMongo == 0.5.1 Flask-Session == 0.3.1