Flask Problem: RuntimeError: The session is unavailable because no secret key was set

Flask Problem: RuntimeError: The session is unavailable because no secret key was set

所以我在 mac 上使用 flask_login 作为我的登录系统,我似乎 运行 遇到了问题。当我 运行 代码时,它说我没有设置我的密钥,即使我已经设置了。

我的代码是:

from flask import Flask, render_template, request, session, redirect, url_for, jsonify
from flask_session import Session
from flask_login import LoginManager, login_user,logout_user, login_required, current_user
from models.model import *
from sqlalchemy import or_, and_

app = Flask(__name__)
app.secret_key = "<Some secret key>"
app.config["SQLALCHEMY_DATABASE_URI"] = '<Some Uri>'
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db.init_app(app)
Session(app)

login_manager = LoginManager()
login_manager.login_view = 'index'
login_manager.init_app(app)

@app.route("/")
def index():
    if current_user.is_authenticated:
        return render_template("home.html")
    return render_template("login.html", tip="You have to log in first.")

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

@app.route("/login", methods=['POST'])
def verif():
    """ Gets name and password from form  """
    username = request.form.get("username")
    password = request.form.get("password")

    """ Checks user and password. """

    userpassCheck = User.query.filter(and_(User.username == username, User.password == password)).first()
    if not userpassCheck:
        return render_template("index.html", tip="Incorrect Username or Password.")

    login_user(userpassCheck)

    return redirect(url_for('index'))

if __name__ == '__main__':
    app.run(debug=True, use_reloader=True)

整个错误回溯是:

Traceback (most recent call last):
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/app.py", line 2464, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/app.py", line 2450, in wsgi_app
    response = self.handle_exception(e)
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/app.py", line 1867, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/scythia/Desktop/Project1/application.py", line 54, in verif
    login_user(userpassCheck)
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask_login/utils.py", line 170, in login_user
    session['_user_id'] = user_id
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/werkzeug/local.py", line 350, in __setitem__
    self._get_current_object()[key] = value
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/sessions.py", line 103, in _fail
    "The session is unavailable because no secret "
RuntimeError: The session is unavailable because no secret key was set.  Set the secret_key on the application to something unique and secret.

我对代码的期望是它完全能够 运行。我没有包含这两个 HTML 文件,因为我认为它们不相关。觉得可以的话我可以加

使用: Python3.7.7; 烧瓶 1.1.2;

正如@Harmandeep Kalsi 在评论中所说,我添加了 app.config['SESSION_TYPE'] 并且有效。

对于在其他答案后仍然出现错误的其他人,如果您使用的格式是 app.confing['<string>'],请确保在“SECRET”和“KEY”之间包含下划线。

这最终成为我的问题,但它会导致相同的错误代码,因此搜索它会将我带到这里。所以,我想我会为将来遇到这个问题的任何人提供我的解决方案。

所以对我有用的是切换:

app.config['SECRET KEY']

与:

app.config['SECRET_KEY']