未在 Flask 会话中设置密钥,使用 Flask-Session 扩展 [英] secret key not set in flask session, using the Flask-Session extension

查看:21
本文介绍了未在 Flask 会话中设置密钥,使用 Flask-Session 扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

运行时错误:会话不可用,因为没有密钥放.将应用程序上的 secret_key 设置为唯一的并且秘密.

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

下面是我的服务器代码.

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?

还有其他会话选项吗?

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

Other info: Running Python 2.7 on Linux Mint

完整粘贴:

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.

推荐答案

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

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

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

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

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

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

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

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

if __name__ == "__main__":
    # Quick test configuration. Please use proper Flask configuration options
    # in production settings, and use a separate file or environment variables
    # to manage the secret key!
    app.secret_key = 'super secret key'
    app.config['SESSION_TYPE'] = 'filesystem'

    sess.init_app(app)

    app.debug = True
    app.run()

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

If you see this error and you are not using Flask-Session, then something has gone wrong with setting the secret. If you are setting app.config['SECRET_KEY'] or app.secret_key in 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 应用程序的配置总是更好一个单独的文件,无论如何.

这篇关于未在 Flask 会话中设置密钥,使用 Flask-Session 扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆