LoginSignup
2
1

More than 5 years have passed since last update.

webapp2でmain.pyからroutesを分離する

Last updated at Posted at 2018-02-16

※2016年6月25日に書いたブログ記事からの転記です。

Google App Engine + Pythonでウェブアプリケーションをつくるときは大抵webapp2フレームワークを使用するのですが、リクエストハンドラーが多くなるとmain.pyがルーティングの設定で埋め尽くされて読みづらくなるので、別のファイルに記述して読み込ませるようにしています。

具体的には以下のように書いています。

まずはルーティング設定を routes.py に記述します。

from webapp2_extras.routes import RedirectRoute

routes = [
    # ホーム
    RedirectRoute(
        '/',
        handler='handlers.IndexHandler',
    ),

    # フィード
    RedirectRoute(
        '/feed.rss',
        handler='handlers.FeedRSSHandler',
    ),

    # sitemap.xml
    RedirectRoute(
        '/sitemap.xml',
        handler='handlers.SitemapXMLHandler',
    ),
]

def get_routes():
    return routes

main.py では以下のようにします。

import os
import webapp2
from webapp2_extras import jinja2
from lib import jinja2_filters
import routes

class BaseHandler(webapp2.RequestHandler):

    @webapp2.cached_property
    def jinja2(self):
        return jinja2.get_jinja2(app=self.app)

    def render_template(self, _template, **context):
        context['env'] = os.environ
        self.response.write(
            self.jinja2.render_template(_template, **context)
        )

    def get_rendered_template(self, _template, **context):
        return self.jinja2.render_template(_template, **context)

config = {
    # Jinja2 テンプレートエンジンの設定
    'webapp2_extras.jinja2': {
        # テンプレートファイルのパス
        'template_path': [
            'templates',
        ],
        # カスタムフィルターの読み込み
        'filters': {
            'jst': jinja2_filters.jst,
            'datetimeformat': jinja2_filters.datetimeformat,
            'nl2br': jinja2_filters.nl2br,
            'markdown2html': jinja2_filters.markdown2html,
        },
    },
}

app = webapp2.WSGIApplication(
    routes=routes.get_routes(),
    debug=os.environ['DEBUG_MODE'],
    config=config
)

最初の方で import routes して routes.py をインポートして、最後の方の routes=routes.get_routes() でルーティング設定を読み込ませています。

以上です。

2
1
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
2
1