LoginSignup
8
6

More than 5 years have passed since last update.

python/tornadoでカスタムしたエラーページを使う

Last updated at Posted at 2014-05-08

python/tornadoでカスタムエラーページを扱う際に少々はまったのでまとめ。

# -*- coding: utf-8 -*-
import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    # self.write_errorをオーバーライド
    def write_error(self, status_code, exc_info=None, **kwargs):
        self.set_header('Content-Type', 'text/html; charset="utf-8"') # 適宜content-typeを宣言(optional)
        if status_code == 503:
            # 直接書いてもいいし、
            self.finish('<h1>503 Service Temporarily Unavailable</h1>')
        elif status_code == 404:
            # テンプレートを別途用意してもいい
            self.render('/path/to/templates_dir/404.html',
                # テンプレート中に埋め込む変数をキーワード引数渡しする
                message = 'hogehoge'
            )
        # 中略...

    def get(self):
        # 中略...

application = tornado.web.Application([
    # 中略...
])

if __name__ == "__main__":
    application.listen(port=8080)
    tornado.ioloop.IOLoop.instance().start()

まとめ

  • オーバーライドしたwrite_error内ではself.finish()で〆る
  • self.render()は内部でself.finish()を呼ぶので無問題
8
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
6