Flask on Heroku でセッションを使う際の設定

EC2上では動作したのにHeroku上へ移した時に以下のエラーが出るようになった。

Traceback (most recent call last):
  File "/app/blueprint/pages.py", line 51, in valid_login
    session['username'] = user['username']
  File "/app/.heroku/python/lib/python2.7/site-packages/werkzeug/local.py", line 341, in __setitem__
    self._get_current_object()[key] = value
  File "/app/.heroku/python/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.

調べたところFlask-Sessionという拡張モジュールを利用するそう。

pip install Flask-Session

今回はMongoLabアドオンを使用していたためSESSIN_TYPEを変えるとファイルやDBに保存できるっぽい。 以下のようにfilesystemを指定した場合はflask_sessionディレクトリが作成されてそこに保存される。

SESSION_TYPE = 'filesystem'
app.config.from_object(__name__)
Session(app)

今回はMongoLabを使用していたためmongodbに設定したかったけれどHeroku上で以下のエラーが発生。

SESSION_TYPE = 'mongodb'
SESSION_PERMANENT = True
MONGOLAB_URI = os.environ.get('MONGOLAB_URI', None)
if MONGOLAB_URI:
    SESSION_MONGODB = MONGOLAB_URI.split('/')[2]
    SESSION_MONGODB_DB = MONGOLAB_URI.split('/')[3]
    SESSION_MONGODB_COLLECT = 'sessions'
Traceback (most recent call last):
  File "/app/.heroku/python/bin/gunicorn", line 11, in <module>
    sys.exit(run())
  File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 74, in run
    WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run()
  File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/base.py", line 189, in run
    super(Application, self).run()
  File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/base.py", line 72, in run
    Arbiter(self).run()
  File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 201, in run
    self.halt(reason=inst.reason, exit_status=inst.exit_status)
  File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 297, in halt
    self.stop()
  File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 342, in stop
    time.sleep(0.1)
  File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 214, in handle_chld
    self.reap_workers()
    raise HaltServer(reason, self.WORKER_BOOT_ERROR)
gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
  File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 459, in reap_workers

ローカルだと動くんだけど原因がわからん。。。 気が向いたら調べます。