pallets-eco / flask-session

Server side session extension for Flask
https://flask-session.readthedocs.io
BSD 3-Clause "New" or "Revised" License
501 stars 239 forks source link

can't compare offset-naive and offset-aware datetimes #85

Closed GuyShaanan closed 8 months ago

GuyShaanan commented 6 years ago

I'm using flask-session with MongoDB (with the help of Flask-PyMongo). Flask-PyMongo uses timezone-aware datetime objects.

From its docs:

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.


flask == 0.12.2 Flask-PyMongo == 0.5.1 Flask-Session == 0.3.1

Lxstr commented 8 months ago

This should be fixed in 0.6.0 by forcing all pymongo datetimes to be tz_aware knowing that pymongo returns always utc time.