我有一个非常基本的烧瓶应用程序,已部署到Heroku。我正在尝试定义一个变量,在执行特定功能时可以更改。例如,如果我有一个变量logged_in=True
,则我希望能够在执行路由logged_in=False
时将其更改为@app.route('/logout')
。这是代码:
import os
from flask import Flask, session, request, redirect, url_for, flash, g
from flask import render_template
from flask_session import Session
app = Flask(__name__)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
app.config['logged_in']=True
Session(app)
# Redirect to /login route
@app.route('/')
def index():
return redirect(url_for("login"))
# Open main login page
@app.route("/login", methods=["POST","GET"])
def login():
return render_template("login.html")
# Verify login credentials
@app.route("/login_check",methods=["POST"])
def login_check():
return redirect(url_for("main_page"),code=307) if app.config['logged_in']==True else render_template("not_logged_in.html")
@app.route("/main_page", methods=["POST"])
def main_page():
return render_template("main_page.html",name="Main page")
@app.route("/log_out", methods=["POST"])
def log_out():
app.config['logged_in']=False
return redirect(url_for("login"))
if __name__ == '__main__':
app.run(debug=True)
当我在本地启动应用程序时,执行logged_in
时False
的值设置为logout
,如果再次触发login
则该值不变。但是,当我将应用程序部署到Heroku时,再次触发logged_in
时,True
的值会返回login
(很奇怪,该值有时会更改,但并不总是更改)。>
如何设置logged_in
的值,以使其在使用函数更新之前不会改变?我尝试使用session.config['logged_in']
代替app.config['logged_in']
,但是遇到了同样的问题。理想情况下,我希望每个会话的值都是唯一的。
谢谢
答案 0 :(得分:0)
如果要为每个会话存储一个值。建议不要使用像redis
这样的sql。
import os
from flask import Flask, session, request, redirect, url_for, flash, g
from flask import render_template
from flask_session import Session
import redis
app = Flask(__name__)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
app.config['SESSION_TYPE'] = 'redis'
app.config['SESSION_REDIS'] = redis.from_url('127.0.0.1:6379')
# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
app.config['logged_in']=True
Session(app)
# Redirect to /login route
@app.route('/')
def index():
return redirect(url_for("login"))
# Open main login page
@app.route("/login", methods=["POST","GET"])
def login():
return render_template("login.html")
# Verify login credentials
@app.route("/login_check",methods=["POST"])
def login_check():
return redirect(url_for("main_page"),code=307) if app.config['logged_in']==True else render_template("not_logged_in.html")
@app.route("/main_page", methods=["POST"])
def main_page():
return render_template("main_page.html",name="Main page")
@app.route("/log_out", methods=["POST"])
def log_out():
session['key'] = 'False'
return redirect(url_for("login"))
if __name__ == '__main__':
app.run(debug=True)