现在我正在使用 flask 3rd 方库 Flask-Session而且我没有运气让 session 正常工作。
当我连接到我的网站时,我收到以下错误:
RuntimeError: the session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret.
下面是我的服务器代码。
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()
如您所见,我确实设置了应用程序 key 。我做错了什么?
还有其他 session 选项吗?
其他信息: 在 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.
最佳答案
在您的情况下,NullSessionInterface
session 实现引发了异常,这是您使用 Flask-Session 时的默认 session 类型。那是因为您实际上从未将 SESSION_TYPE
配置 提供给 Flask;在您的模块中将其设置为全局是不够。 Flask-Session quickstart example code确实设置了一个全局,但随后通过调用 app.config.from_object(__name__)
将当前模块用作配置对象。
这个默认值对于 Flask 0.10 或更高版本没有多大意义; NullSession
可能对 Flask 0.8 或 0.9 有意义,但在当前版本中 flask.session.NullSession
class用作错误信号。在您的情况下,它现在会给您错误的错误消息。
将 SESSION_TYPE
配置选项设置为其他值。选择 redis
、memcached
、filesystem
或 mongodb
之一,并确保在 app 中进行设置.config
(直接或通过 various Config.from_*
methods )。
为了快速测试,将其设置为 filesystem
是最简单的;那里有足够的默认配置可以在没有额外依赖项的情况下工作:
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__"
block 永远不会运行。
manage configuration for Flask apps in a separate file 总是更好,无论如何。
关于python - 使用 Flask-Session 扩展,未在 flask session 中设置 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26080872/