2
votes

I have configured the session in my app.py as follows.

#Import framework classes
from flask import Flask, request, session
import json
from datetime import timedelta
from flask_pymongo import PyMongo
from flask_mongo_sessions import MongoDBSessionInterface

#Import custom classes
import sys
sys.path.insert(1, './models')
from StudentModel import*

#App initiate, set app configurations and session configurations
app = Flask(__name__, static_url_path='')
app.config["MONGO_URI"] = "mongodb://localhost:27017/ChatBot"
app.config['SESSION_PERMANENT'] = False
mongo = PyMongo(app)
with app.app_context():
    app.session_interface = MongoDBSessionInterface(app, mongo.db, 'sessions')

#Initialize Helper Classes
StudentModelContract = StudentModel(mongo)

@app.route('/getSession')
def getMessage():
    return session['key']

@app.route('/setSession')
def setMessage():
    return session['key'] = 'value'

Now when I'm calling getSession method I'm getting the following error.

Traceback (most recent call last): File "/home/thathsara/Documents/PythonProject/venv/lib/python3.5/site-packages/flask/app.py", line 2446, in wsgi_app ctx.push() File "/home/thathsara/Documents/PythonProject/venv/lib/python3.5/site-packages/flask/ctx.py", line 390, in push self.session = session_interface.open_session(self.app, self.request) File "/home/thathsara/Documents/PythonProject/venv/lib/python3.5/site-packages/flask_mongo_sessions/init.py", line 57, in open_session session = self.session_class(initial=doc['d'], sid=sid) File "/home/thathsara/Documents/PythonProject/venv/lib/python3.5/site-packages/flask_mongo_sessions/init.py", line 18, in init initial = pickle.loads(str(initial)) TypeError: a bytes-like object is required, not 'str' [2020-05-08 17:27:36,960] ERROR in app: Request finalizing failed with an error while handling an error Traceback (most recent call last): File "/home/thathsara/Documents/PythonProject/venv/lib/python3.5/site-packages/flask/app.py", line 2446, in wsgi_app ctx.push() File "/home/thathsara/Documents/PythonProject/venv/lib/python3.5/site-packages/flask/ctx.py", line 390, in push self.session = session_interface.open_session(self.app, self.request) File "/home/thathsara/Documents/PythonProject/venv/lib/python3.5/site-packages/flask_mongo_sessions/init.py", line 57, in open_session session = self.session_class(initial=doc['d'], sid=sid) File "/home/thathsara/Documents/PythonProject/venv/lib/python3.5/site-packages/flask_mongo_sessions/init.py", line 18, in init initial = pickle.loads(str(initial)) TypeError: a bytes-like object is required, not 'str'

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "/home/thathsara/Documents/PythonProject/venv/lib/python3.5/site-packages/flask/app.py", line 1970, in finalize_request response = self.process_response(response) File "/home/thathsara/Documents/PythonProject/venv/lib/python3.5/site-packages/flask/app.py", line 2269, in process_response self.session_interface.save_session(self, ctx.session, response) File "/home/thathsara/Documents/PythonProject/venv/lib/python3.5/site-packages/flask_mongo_sessions/init.py", line 68, in save_session cookie_exp = self.get_expiration_time(app, session) File "/home/thathsara/Documents/PythonProject/venv/lib/python3.5/site-packages/flask/sessions.py", line 268, in get_expiration_time if session.permanent: AttributeError: 'NoneType' object has no attribute 'permanent'

The first time without any session the application is running properly and once I set a session it will be created in the DB as well as the session id is sent to the browser without any issue (cookie). But after that I'm getting above error even I call another route (even /). Can someone explain what is the issue with my code?

1
I tried running the code you have provided. Are you not getting an error for the line return session['key'] = 'value' ? - Sumedh Patkar

1 Answers

0
votes

I found the issue while my later investigations. The main flask_mongo_session lib is using the following class while opening the session.

class MongoDBSession(CallbackDict, SessionMixin):
def __init__(self, initial=None, sid=None, new=True):
    def on_update(this):
        this.modified = True
    if initial:
        initial = pickle.loads(str(initial))
    CallbackDict.__init__(self, initial, on_update)
    self.sid = sid
    self.new = new
    self.modified = False

def pack(self):
    return Binary(pickle.dumps(dict(self)))

Here the following line has an issue.

initial = pickle.loads(str(initial))

Changed it to,

initial = pickle.loads((initial))