未在Flask会话中使用Flask-Session扩展名设置秘密密钥 [英] secret key not set in flask session, using the Flask-Session extension
问题描述
现在我正在使用Flask第三方库 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:
RuntimeError:会话不可用,因为没有密钥 放.将应用程序上的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_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可能是有意义的,但在当前版本中,
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
配置选项设置为其他选项.选择redis
,memcached
,filesystem
或mongodb
之一,并确保将其设置在app.config
中(直接或通过
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__":
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屋!