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

现在我正在使用一个烧瓶第三方库 烧瓶-会议,我没有运气得到一个会议工作。

当我连接到我的网站,我得到以下错误:

RuntimeError: 会话不可用,因为没有密钥 将应用程序上的 secret _ key 设置为惟一的并且 秘密。

下面是我的服务器代码。

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()

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

还有其他会话选项吗?

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

全面粘贴:

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.
153068 次浏览

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__).

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.

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).

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()

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.

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

Try this:

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

And remove your app.secret_key assignment at the bottom.

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

app.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 run the if __name__ == '__main__': block gets skipped. If you don't want to skip it, run with python app.py.