[英]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.
正如您在下面的代码中看到的那样,在 main 中,我首先导入了所有东西所需的所有库,然后在 i_setup_functions.py 文件中复制了这些导入。 Leaving any of them out of either file created errors.
将其中任何一个排除在任一文件之外都会导致错误。 Same with duplication of "app = Flask( name )".
与“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.该错误消息指向 main.py 中间试图创建会话的函数中的一行。
Thanks for any ideas you all can share!感谢大家可以分享的任何想法!
main.py:主要.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 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
You are creating two (or more?) separate apps and setting the SECRET_KEY
to the one that isn't serving your application.您正在创建两个(或更多?)单独的应用程序并将
SECRET_KEY
设置为不为您的应用程序提供服务的应用程序。
To fix this remove all app = Flask(__name__)
calls from all modules except main.py
.要解决此问题,请从除
main.py
之外的所有模块中删除所有app = Flask(__name__)
调用。 Then, pass the app
you create in main.py
to all the places you need it.然后,将您在
main.py
创建的app
传递到您需要的所有地方。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.