Skip to content

Commit 603e569

Browse files
committed
MongoEngineSessionInterface can now handle PyMongo configs with TZ_AWARE set to true.
1 parent 8c489c2 commit 603e569

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

flask_mongoengine/sessions.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
from flask.sessions import SessionInterface, SessionMixin
66
from werkzeug.datastructures import CallbackDict
7+
from bson.tz_util import utc
78

89
__all__ = ("MongoEngineSession", "MongoEngineSessionInterface")
910

@@ -57,8 +58,16 @@ def open_session(self, app, request):
5758
sid = request.cookies.get(app.session_cookie_name)
5859
if sid:
5960
stored_session = self.cls.objects(sid=sid).first()
60-
if stored_session and stored_session.expiration > datetime.datetime.utcnow():
61-
return MongoEngineSession(initial=stored_session.data, sid=stored_session.sid)
61+
62+
if stored_session:
63+
expiration = stored_session.expiration
64+
65+
if not expiration.tzinfo:
66+
expiration = expiration.replace(tzinfo=utc)
67+
68+
if expiration > datetime.datetime.utcnow().replace(tzinfo=utc):
69+
return MongoEngineSession(initial=stored_session.data, sid=stored_session.sid)
70+
6271
return MongoEngineSession(sid=str(uuid.uuid4()))
6372

6473
def save_session(self, app, session, response):
@@ -70,7 +79,7 @@ def save_session(self, app, session, response):
7079
response.delete_cookie(app.session_cookie_name, domain=domain)
7180
return
7281

73-
expiration = datetime.datetime.now() + self.get_expiration_time(app, session)
82+
expiration = datetime.datetime.utcnow().replace(tzinfo=utc) + self.get_expiration_time(app, session)
7483

7584
if session.modified:
7685
self.cls(sid=session.sid, data=session, expiration=expiration).save()

0 commit comments

Comments
 (0)