[英]Flask-login users are being logged out at random when app is live (not when run local)
I have a Flask app, with user Authentication.我有一个 Flask 应用程序,带有用户身份验证。 Its working fine when run in a venv but as soon as i deploy it as a google cloud app it starts logging users out at random, sometimes it can be minutes and other times it at one of the first requests.
它在 venv 中运行时工作正常,但是一旦我将它部署为谷歌云应用程序,它就会开始随机注销用户,有时可能是几分钟,有时是在第一个请求中。
Here are the most central parts of my app, I beleive the error must be here or in the App Engine configuration.这是我的应用程序最核心的部分,我相信错误一定是在这里或在 App Engine 配置中。
db=SQLAlchemy()
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(12)
app.config['SQLALCHEMY_DATABASE_URI'] = "my_db_uri"
db.init_app(app)
from .views import views
from .auth import auth
app.register_blueprint(views, url_prefix='/')
app.register_blueprint(auth, url_prefix='/')
from .models import User
login_manager = LoginManager(app)
login_manager.login_view = 'auth.login'
login_manager.init_app(app)
@login_manager.user_loader
def load_user(id):
return User.query.get(int(id))
return app
app = create_app()
if __name__ == '__main__':
app.run(debug=True)
this link should show you how to set up environment variables on a production environment.此链接应向您展示如何在生产环境中设置环境变量。 https://dev.to/sasicodes/flask-and-env-22am
https://dev.to/sasicodes/flask-and-env-22am
I think you are missing the os.getenv()
which can be found by installing the dotenv
module using pip install python-dotenv
and importing it in your file either the config.py
file or the file with the app engine configuration.我认为您缺少
os.getenv()
,可以通过使用pip install python-dotenv
dotenv
模块并将其导入到您的文件中,无论是config.py
文件还是带有应用程序引擎配置的文件。
you can use the os.getenv as such你可以这样使用 os.getenv
`
from dotenv import load_dotenv
load_dotenv()
db=SQLAlchemy()
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY'] = os.getenv("my_secret_key")
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv("my_db_uri")
db.init_app(app)
from .views import views
from .auth import auth
app.register_blueprint(views, url_prefix='/')
app.register_blueprint(auth, url_prefix='/')
from .models import User
login_manager = LoginManager(app)
login_manager.login_view = 'auth.login'
login_manager.init_app(app)
@login_manager.user_loader
def load_user(id):
return User.query.get(int(id))
return app
app = create_app()
if __name__ == '__main__':
app.run(debug=True)
` `
I was using os.urandom() to generate a random secret key in a settings file.我正在使用 os.urandom() 在设置文件中生成随机密钥。
The problem was solved when I changed it to a string.当我将其更改为字符串时,问题就解决了。
I guess the problem was that App Engine is running several instances and got differend secret keys from time to time, which made the session cookie invalid and therefor cleared the cookie content.我猜问题是 App Engine 正在运行多个实例并且不时获得不同的密钥,这使得 session cookie 无效,因此清除了 cookie 内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.