差分
このページの2つのバージョン間の差分を表示します。
| 次のリビジョン | 前のリビジョン | ||
| python:django:cache_page_with_bpmobile [2011/06/19 23:42] – 作成 ともやん | python:django:cache_page_with_bpmobile [2019/08/19 07:01] (現在) – ともやん | ||
|---|---|---|---|
| 行 1: | 行 1: | ||
| - | ====== PCとモバイルで切り替わるキャッシュページデコレータ ====== | + | ====== |
| - | ここでは django-bpmobile を組み合わせた | + | 同一URLでPCとモバイルでキャッシュページを切り替えるには、Varyヘッダを利用する方法などが考えられますが、\\ |
| + | ここでは django-bpmobile を組み込んでいる場合に利用できる agent 判定を組み込んだ | ||
| + | (agentの判定方法次第でキャリアごとにキャッシュすることも可能です。) | ||
| + | <code python> | ||
| + | # -*- coding: utf-8 -*- | ||
| + | try: | ||
| + | from functools import wraps | ||
| + | except ImportError: | ||
| + | from django.utils.functional import wraps # Python 2.4 fallback. | ||
| + | |||
| + | from django.utils.decorators import available_attrs | ||
| + | from django.views.decorators.cache import cache_page | ||
| + | |||
| + | def cache_page_with_bpmobile(cache_timeout, | ||
| + | """ | ||
| + | def __cache_page_with_bpmobile(view_func): | ||
| + | # 引数 view_func をラップする関数を定義 | ||
| + | @wraps(view_func, | ||
| + | def _cache_page_with_bpmobile(request, | ||
| + | # モバイル以外の場合 | ||
| + | if request.agent.is_nonmobile(): | ||
| + | # モバイル以外のキープリフィックスを設定 | ||
| + | cache_key_prefix = nonmobile_key_prefix | ||
| + | # モバイルの場合 | ||
| + | else: | ||
| + | # モバイルのキープリフィックスを設定 | ||
| + | cache_key_prefix = mobile_key_prefix | ||
| + | # キープリフィックスを指定してcache_pageに処理を委託 | ||
| + | return cache_page(view_func, | ||
| + | return _cache_page_with_bpmobile | ||
| + | return __cache_page_with_bpmobile | ||
| + | |||
| + | </ | ||
| + | @cache_page_with_bpmobile デコレータは以下ように利用する。\\ | ||
| + | \\ | ||
| + | views.py | ||
| + | <code python> | ||
| + | @cache_page_with_bpmobile(cache_timeout=60*60, | ||
| + | def top_page(): | ||
| + | ... | ||
| + | </ | ||