ScotterMonkey
ScotterMonkey

Reputation: 1044

Python 3.8 module duplication and app object scope within imported functions

I'm confused about import of custom modules. As you can see in the code below, in main I first import all libraries needed by everything AND that I duplicated those imports in my i_setup_functions.py file. Leaving any of them out of either file created errors. Same with duplication of "app = Flask(name)". I really hope that redundancy is not correct and there is some simple way to fix this. All I want to do is include setup for sessions, email, data connection, etc. Only showing sessions here for simplicity sake.

BTW: The entire app worked bug-free until I tried to modularize.

Error message:

RuntimeError: The session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret.

That error message points to a line in a function in the middle of main.py that tries to create a session.

Thanks for any ideas you all can share!

main.py:

from flask import session
import random
from datetime import datetime, timedelta
from i_setup_functions import setup_sessions

app = Flask(__name__)
# is the following line even necessary in either module?
application = app

setup_sessions()
setup_mail()
setup_logging()
[snip]
# Error here:
​session["id_user"] = id_user

i_setup_functions.py

from flask import session
import random
from datetime import datetime, timedelta
from i_setup_functions import setup_sessions

app = Flask(__name__)
application = app

def setup_sessions():
    random.seed(datetime.now())
    app.config['SECRET_KEY'] = str(random.randint(1, 500)) + "jibber" + str(random.randint(1, 500)) + "jabber"
    app.permanent_session_lifetime = timedelta(days=30)
    return True

Upvotes: 1

Views: 69

Answers (1)

Simeon Nedkov
Simeon Nedkov

Reputation: 1094

You are creating two (or more?) separate apps and setting the SECRET_KEY to the one that isn't serving your application.

To fix this remove all app = Flask(__name__) calls from all modules except main.py. Then, pass the app you create in main.py to all the places you need it.

from flask import session
import random
from datetime import datetime, timedelta
from i_setup_functions import setup_sessions

app = Flask(__name__)

setup_sessions(app)
setup_mail(app)
setup_logging(app)

[snip]

​session["id_user"] = id_user

Upvotes: 2

Related Questions