Python + Flask在请求上下文之外工作

时间:2018-03-22 02:28:18

标签: python flask

我有这个python代码,我试图将用户试图访问我的网站主页(例如http://example.com/)重定向到他们的个人资料页面,如果他们已登录,但我收到此异常在第13行。

  

RuntimeError:在请求上下文之外工作。

如果我删除第13行,我会收到一个不同的例外。

  

KeyError:' user_id'

from cs50 import SQL
from flask import Flask, flash, redirect, render_template, request, session
from flask_session import Session
from tempfile import mkdtemp
from werkzeug.exceptions import default_exceptions
from werkzeug.security import check_password_hash, generate_password_hash

app = Flask(__name__)
app.secret_key = "super secret key"
app.config["SESSION_TYPE"] = "filesystem"
db = SQL("sqlite:///data.db")
Session(app)
session['user_id'] = 0

@app.route("/")
def index():
    if session['user_id'] != 0:
        return redirect("profile/" + session['username'])
    return render_template("index.html")


@app.route("/login", methods=["GET", "POST"])
def login():
    """Log user in"""

    # Forget any user_id
    session.clear()
    session['user_id'] = 0
    # User reached route via POST (as by submitting a form via POST)
    if request.method == "POST":

        # Ensure username was submitted
        if not request.form.get("username"):
            return apology("must provide username", 403)

        # Ensure password was submitted
        elif not request.form.get("password"):
            return apology("must provide password", 403)

        # Query database for username
        rows = db.execute("SELECT * FROM users WHERE username = :username",
                          username=request.form.get("username"))

        # Ensure username exists and password is correct
        if len(rows) != 1 or not check_password_hash(rows[0]["passwordHash"], request.form.get("password")):
            return apology("invalid username and/or password", 403)

        # Remember which user has logged in
        session["user_id"] = rows[0]["id"]
        session["username"] = rows[0]["username"]

        return redirect("/")

1 个答案:

答案 0 :(得分:2)

session['user_id'] = 0位于请求上下文主体之外。

您应该将if session['user_id'] != 0:替换为if session.get('user_id',0) != 0:,以获取会话的默认值。因此修复KeyError

然后,您不需要初始化任何会话密钥