angrykola

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

视图和URL配置:

创建视图文件 

紧接着笔记一的内容,在已经创建的mysitew文件夹中创建一个views.py的文件,负责进行视图的配置。(Django对于view.py的文件命名没有特别的要求,它不在乎这个文件叫什么。但是根据约定,把它命名成view.py是个好主意,这样有利于其他开发者读懂你的代码

#views.py
from django.http import HttpResponse

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

创建URLconf

 现在,如果你再运行:python manage.py runserver,你还将看到Django的欢迎页面,而看不到我们刚才写的Hello world显示页面。 那是因为我们的mysite项目还对hello视图一无所知。我们需要通过一个详细描述的URL来显式的告诉它并且激活这个视图。 

from django.conf.urls import patterns, include, url
from mysite.views import hello   #从视图文件中导入hello事件
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',       #patterns() 函数并将返回结果保存到 urlpatterns 变量
    ('^hello/$',hello),          #正则表达式(后面会有专门的笔记写到)
    '''
这行被称作URLpattern,它是一个Python的元组。元组中第一个元素是模式匹配字符串(正则表达式);第二个元素是那个模式将使用的视图函数。
    '''
)

之后通过windows powershell 运行 python manage.py runserver,进入http://127.0.0.1:8000/hello 就能看到一个静态的页面。

第二个试图:动态视图

 这个视图将会将一些动态的东西例如当前日期和时间显示在网页上。

from django.http import HttpResponse
import datetime
...  
def current_datetime(request):
    now = datetime.datetime.now
    html = '<html><body>It is now %s.</body></html>' %now
    return HttpResponse(html)

再将('^time/',current_datetime)添加进urls.py模块,然后运行服务器,进入http://127.0.0.1:8000/time/ 页面,就能看到一个显示当前时间的页面。

URL配置和松耦合

 django简介的url也是其的一大特色,在Django的应用程序中,URL的定义和视图函数之间是松 耦合的,换句话说,决定URL返回哪个视图函数和实现这个视图函数是在两个不同的地方。 这使得 开发人员可以修改一块而不会影响另一块。

例如:在urls.py 模块中添加 

('^time/',current_datetime),
('^hehehehe/',current_datetime),

则 http://127.0.0.1:8000/time/ 与 http://127.0.0.1:8000/hehehehe 指向相同页面

 

第三个视图 动态URL

 有时候可能会写同的视图函数来处理每个时间偏差量,URL配置看起来就象这样:

urlpatterns = patterns('',
    ('^time/$', current_datetime),
    ('^time/plus/1/$', one_hour_ahead),
    ('^time/plus/2/$', two_hours_ahead),
    ('^time/plus/3/$', three_hours_ahead),
    ('^time/plus/4/$', four_hours_ahead),
)

这样的话明显代码冗余太多,不便于维护。

现在将视图函数 和 url 做如下修改:

(r'^time/plus/(\d{1,2})/$', hours_ahead),

继续修改view:

def hours_ahead(request,offset): #hours_ahead , 有 两个 参数: request 和 offset 
    try:
        offset = int(offset) #offset 是从匹配的URL里提取出来的。同时将offect通过int函数转换成整数 
                    #例如:如果请求URL是/time/plus/3/,那么offset将会是3
    except:
        raise Http404()
    dt = datetime.datetime.now() + datetime.timedelta(hours=offset) 
    html = '<html><body>It will be %s ,after %s hours later.' %(dt,offset)
    return HttpResponse(html)

现在打开 http://127.0.0.1:8000/time/a/b/11  就能看到11小时候的时间。

 

(Django学习笔记主要参考与 The Django Book http://djangobook.py3k.cn/2.0/ 、Django中文文档 http://django-chinese-docs.readthedocs.org/en/latest/

posted on 2013-11-12 23:47  kolaman  阅读(183)  评论(0)    收藏  举报