Python 未在烧瓶会话中设置密钥,使用 Flask-Session 扩展

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26080872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:02:31  来源:igfitidea点击:

secret key not set in flask session, using the Flask-Session extension

pythonsessionflask

提问by MintyAnt

Right now I am using a flask 3rd party library Flask-Sessionand I am having no luck getting a session working.

现在我正在使用Flask3rd 方库Flask-Session并且我没有运气让会话工作。

When I connect to my site, I get the following error:

当我连接到我的网站时,出现以下错误:

RuntimeError: the session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret.

运行时错误:会话不可用,因为未设置密钥。将应用程序上的 secret_key 设置为独一无二的秘密。

Below is my server code.

下面是我的服务器代码。

from flask import Flask, session
from flask.ext.session import Session

SESSION_TYPE = 'memcache'

app = Flask(__name__)
sess = Session()

nextId = 0

def verifySessionId():
    global nextId

    if not 'userId' in session:
        session['userId'] = nextId
        nextId += 1
        sessionId = session['userId']
        print ("set userid[" + str(session['userId']) + "]")
    else:
        print ("using already set userid[" + str(session['userId']) + "]")
    sessionId = session.get('userId', None)
    return sessionId

@app.route("/")
def hello():
    userId = verifySessionId()
    print("User id[" + str(userId) + "]")
    return str(userId)

if __name__ == "__main__":
    app.secret_key = 'super secret key'

    sess.init_app(app)

    app.debug = True
    app.run()

As you can see, I do set the app secret key. What am I doing wrong?

如您所见,我确实设置了应用程序密钥。我究竟做错了什么?

Are there other session options?

还有其他会话选项吗?

Other info: Running Python 2.7 on Linux Mint

其他信息:在 Linux Mint 上运行 Python 2.7

Full paste:

全贴:

Traceback (most recent call last):
  File "/home/sean/code/misc/hangman/venv/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/sean/code/misc/hangman/venv/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/home/sean/code/misc/hangman/venv/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/home/sean/code/misc/hangman/venv/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/sean/code/misc/hangman/venv/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/sean/code/misc/hangman/venv/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/sean/code/misc/hangman/venv/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/sean/code/misc/hangman/venv/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/sean/code/misc/session/sessiontest.py", line 27, in hello
    userId = verifySessionId()
  File "/home/sean/code/misc/session/sessiontest.py", line 16, in verifySessionId
    session['userId'] = nextId
  File "/home/sean/code/misc/hangman/venv/lib/python2.7/site-packages/werkzeug/local.py", line 341, in __setitem__
    self._get_current_object()[key] = value
  File "/home/sean/code/misc/hangman/venv/lib/python2.7/site-packages/flask/sessions.py", line 126, in _fail
    raise RuntimeError('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.

采纳答案by Martijn Pieters

In your case the exception is raised by the NullSessionInterfacesession implementation, which is the default session typewhen you use Flask-Session. That's because you don't ever actually give the SESSION_TYPEconfiguration to Flask; it is not enoughto set it as a global in your module. The Flask-Session quickstart example codedoes set a global, but then uses the current module as a configuration object by calling app.config.from_object(__name__).

在您的情况下,NullSessionInterface会话实现引发了异常,这是您使用 Flask-Session 时的默认会话类型。那是因为您实际上从未将SESSION_TYPE配置提供给 Flask;将其设置为模块中的全局变量不够的。所述瓶会话快速启动的示例代码并设置一个全局,但随后通过调用使用当前模块作为配置对象app.config.from_object(__name__)

This default doesn't make much sense with Flask 0.10 or newer; NullSessionmay have made sense with Flask 0.8 or 0.9, but in current version the flask.session.NullSessionclassis used as an error signal. In your case it gives you the wrong error message now.

这个默认值对于 Flask 0.10 或更新版本没有多大意义;NullSession可能对 Flask 0.8 或 0.9 有意义,但在当前版本中,flask.session.NullSession该类用作错误信号。在你的情况下,它现在给你错误的错误信息。

Set the SESSION_TYPEconfiguration option to something else. Pick one of redis, memcached, filesystemor mongodb, and make sure to set it in app.config(directly or via the various Config.from_*methods).

SESSION_TYPE配置选项设置为其他内容。选择redismemcachedfilesystem或 之一mongodb,并确保将其设置app.config(直接或通过各种Config.from_*方法)。

For a quick test, setting it to filesystemis easiest; there is enough default configuration there to have that work without additional dependencies:

对于快速测试,将其设置filesystem为最简单;那里有足够的默认配置可以在没有额外依赖的情况下工作:

if __name__ == "__main__":
    app.secret_key = 'super secret key'
    app.config['SESSION_TYPE'] = 'filesystem'

    sess.init_app(app)

    app.debug = True
    app.run()

If you see this error and you are notusing Flask-Session, then something has gone wrong with setting the secret. If you are setting app.config['SECRET_KEY']or app.secret_keyin a if __name__ == "__main__":guard like above and you get this error, then you are probably running your Flask app via a WSGI server that imports your Flask project as a module, and the __name__ == "__main__"block is never run.

如果您看到此错误并且您没有使用 Flask-Session,则说明设置密钥时出现问题。如果你正在设置app.config['SECRET_KEY']app.secret_keyif __name__ == "__main__":像上面一样的守卫中并且你得到这个错误,那么你可能正在通过一个 WSGI 服务器运行你的 Flask 应用程序,该服务器将你的 Flask 项目作为一个模块导入,并且该__name__ == "__main__"块永远不会运行。

It is always better to manage configuration for Flask apps in a separate file, anyway.

它始终是更好地管理配置瓶的应用程序在一个单独的文件,反正。

回答by Miguel

Try this:

尝试这个:

app = Flask(__name__)
app.config['SESSION_TYPE'] = 'memcached'
app.config['SECRET_KEY'] = 'super secret key'
sess = Session()

And remove your app.secret_keyassignment at the bottom.

app.secret_key在底部删除您的分配。

回答by hayden

Set the secret key outside of if __name__ == '__main__':

将密钥设置在 if __name__ == '__main__':

app.py:

应用程序.py:

from flask import Flask, session

app = Flask(__name__)
app.secret_key = "super secret key"

@app.route("/")
...

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

When you start your app by running flask runthe if __name__ == '__main__':block gets skipped. If you don't want to skip it, run with python app.py.

当您通过运行启动您的应用程序flask runif __name__ == '__main__':块不会被跳过。如果您不想跳过它,请使用python app.py.