Programing

Flask-Session 확장을 사용하여 플라스크 세션에 비밀 키가 설정되지 않았습니다.

lottogame 2020. 11. 8. 09:09
반응형

Flask-Session 확장을 사용하여 플라스크 세션에 비밀 키가 설정되지 않았습니다.


지금은 플라스크 타사 라이브러리 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.

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__":
    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.


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.


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.

참고URL : https://stackoverflow.com/questions/26080872/secret-key-not-set-in-flask-session-using-the-flask-session-extension

반응형