Python+Django+SAEシリーズチュートリアル9----DjangoのビューとURL


第三、四、五章で紹介するのはDjangoのMVCのビュー、テンプレート、モデルです.
まずビュー(view)を見る、Djangoで生成されたウェブサイトフォルダにviewを作成する.pyファイル、このファイルは最初は空です.次に、次のように入力します.
from django.http import HttpResponse

def hello(request):
    return HttpResponse("Hello world")

このファイルではhelloという関数を定義しましたが、これが私たちの最初のビューです.実は1つのビューはPythonの関数です.
    
次に、DjangoがサポートするWebサイトのディレクトリのようなURLconfを作成します.本質は、URLモードと、そのURLモードに呼び出すビュー関数とのマッピングテーブルです.このURLに対してこのコードを呼び出し、そのURLに対してそのコードを呼び出すようにDjangoに伝えます.例えば、ユーザが/foo/にアクセスすると、ビュー関数foo_が呼び出されるview()このビュー関数はPythonモジュールファイルviewに存在する.pyで.
djangoを使用して生成されたWebサイトでurlsを見つけることができます.pyのファイルは、このファイルを開き、ファイルに提示された例に従って、私たちが追加したいパスと対応するビューを追加します.urls全体pyの内容は次のとおりです.
from django.conf.urls import patterns, include, url


# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'Bidding.views.home', name='home'),
    # url(r'^Bidding/', include('Bidding.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
    url(r'^hello/$', 'Bidding.views.hello'),
)

簡単に言えば、Djangoに、URL/hello/を指すすべてのリクエストはhelloというビュー関数で処理されるべきだと伝えただけです.私たちはsvnを使って新しく追加したviewsを使います.pyと修正urls.pyはsaeをアップロードして、このようにあなたの最初のhelloプログラムを見ることができます.
上に示したのは極めて簡単な例で、viewsで同じ考えで動的な内容を作成します.pyファイルにビューを追加するには、次の手順に従います.
import datetime

def current_datetime(request):
    now = datetime.datetime.now()
    html = "<html><body>      %s.</body></html>" % now
    return HttpResponse(html)
が新たに追加されたこのビューでは、現在の時間を出力するために変数nowを使用します.urlsを修正する必要がありますpyこのファイル:
from django.conf.urls import patterns, include, url


# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'Bidding.views.home', name='home'),
    # url(r'^Bidding/', include('Bidding.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
    url(r'^hello/$', 'Bidding.views.hello'),
    url(r'^time/$', 'Bidding.views.current_datetime'),
)

コードをアップロードして、結果http://アプリケーションのアドレス/time/、ここで私たちは中国語を使って、あなたが見た中国語はきっと文字化けして、ここで2つの場所を修正する必要があります:第1はsetting.pyファイルをTIME_ZONE='Asia/Beijing'そしてLANGUAGE_CODE='zh-cn'は、このように修正されました.2つ目は、中国語のファイル(views.py)の上部にこのような行を追加すればいいです.
# -*- coding: utf-8 -*-
次に、動的urlを実現します.3番目のビューを作成して、現在の時間と時間のずれを加えた時間を表示します./time/plus/1/現在の時間+1時間のページを表示/time/plus/2/現在の時間+2時間のページを表示/time/plus/3/現在の時間+3時間のページを表示するように設計されています.
urlsでpyファイルに(r'^time/plus/d{1,2}/$',hours_ahead)を追加すると、その意味がわかるでしょう.正則に詳しくない場合は、まず熟知しておきましょう.ここでは正則式を説明することは多くありません.ここで注意しなければならないのは,ユーザが入力したurlから抽出した数をパラメータとしてビューに渡す必要があることである.上の正則から分かるように、私たちが抽出するのはプラスの時間、すなわち「d{1,2}」という部分(0~99)ですが、正則の選択部分も()ここで、「d{1,2}」をカッコで囲む必要があります(r'^time/plus/(d{1,2})/$',hours_ahead)
from django.conf.urls import patterns, include, url


# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'Bidding.views.home', name='home'),
    # url(r'^Bidding/', include('Bidding.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
    url(r'^hello/$', 'Bidding.views.hello'),
    url(r'^time/$', 'Bidding.views.current_datetime'),
    url(r'^time/plus/(\d{1,2})/$', 'Bidding.views.hours_ahead'),

)
今からhoursを書きます_aheadビュー.
def hours_ahead(request, offset):
    try:
        offset = int(offset)
    except ValueError:
        raise Http404()
    dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
    html = "<html><body>   %s    ,       %s.</body></html>" % (offset, dt)
    return HttpResponse(html)
の上のコードは理解しにくくありません.ここではあまり言いません.上のtryとexceptは誤った情報を隠すためで、プログラマーとしてのあなたはきっと知っています.
ここまで言うと、ビューとURLの理解の基本的な差は多くありませんが、次の章ではテンプレートについて引き続き理解します.