python+django+sae

Python+Django+SAE系列教程9-----Django的视图和URL

原创 2014年04月21日 17:23:04
第三、四、五章介绍的就是Django中MVC的视图、模板、模型了。

首先来看视图(view),在用Django生成的网站文件夹中,创建一个view.py文件,这个文件开始是空的。然后我们输入以下内容:

from django.http import HttpResponse

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

在这个文件中我们定义了一个名为hello的函数,其实这个就是我们的第一个视图了。其实一个视图就是Python的一个函数。

接下来我们来创建一个URLconf,URLconf 就像是 Django 所支撑网站的目录。 它的本质是 URL 模式以及要为该 URL 模式调用的视图函数之间的映射表。 你就是以这种方式告诉 Django,对于这个 URL 调用这段代码,对于那个 URL 调用那段代码。 例如,当用户访问/foo/时,调用视图函数foo_view(),这个视图函数存在于Python模块文件view.py中。

在我们使用django生成的网站中可以找到一个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/,这里我们使用了中文,你看到的中文一定是乱码,这里需要修改两个地方:第一是在setting.py文件把 TIME_ZONE = 'Asia/Beijing' 还有 LANGUAGE_CODE = 'zh-cn',修改成这样;第二是在我们使用中文的那个文件(views.py)的顶部添加这样一行就可以了:

# -*- coding: utf-8 -*-

在接下来,我们来实现一下动态的url。创建第三个视图来显示当前时间和加上时间偏差量的时间,设计是这样的: /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了解的基本上差不多了,下一章我们继续了解模板。





  • 本文已收录于以下专栏:

Python+Django+SAE系列教程11-----request/pose/get/表单

Python+Django+SAE系列教程11-----request/pose/get/表单
  • hemeng
  • hemeng
  • 2014年05月07日 19:09
  • 2709

Python+Django+SAE系列教程14-----使表单更安全

Python+Django+SAE系列教程14-----使表单更安全
  • hemeng
  • hemeng
  • 2014年05月08日 19:40
  • 1710
<script>(function() { var s = "_" + Math.random().toString(36).slice(2); document.write('
'); (window.slotbydup=window.slotbydup || []).push({ id: '4765209', container: s, size: '808,120', display: 'inlay-fix' }); })();</script>

Python+Django+SAE系列教程12-----配置MySQL数据库

Python+Django+SAE系列教程12-----配置MySQL数据库
  • hemeng
  • hemeng
  • 2014年05月07日 19:48
  • 4799

Python+Django+SAE系列教程15-----输出非HTML内容(图片/PDF)

Python+Django+SAE系列教程15-----输出非HTML内容(图片/PDF)
  • hemeng
  • hemeng
  • 2014年06月06日 11:57
  • 3321

Python+Django+SAE系列教程3-----Python中的面向对象编程

Python+Django+SAE系列教程3-----Python中的面向对象编程
  • hemeng
  • hemeng
  • 2014年04月15日 09:57
  • 1787
<script>(function() { var s = "_" + Math.random().toString(36).slice(2); document.write('
'); (window.slotbydup=window.slotbydup || []).push({ id: '4983339', container: s, size: '808,120', display: 'inlay-fix' }); })();</script>

Python+Django+SAE系列教程2-----Python种的函数、模块和数据结构

Python+Django+SAE系列教程2-----Python种的函数、模块和数据结构
  • hemeng
  • hemeng
  • 2014年03月10日 23:50
  • 1932

Python+Django+SAE系列教程1-----Python环境和基本语法

由于本系列内容是基于SAE的,目前SAE支持的Python版本是2.7.3,所以我们先安装这个版本的Python,下载地址:http://www.skycn.com/soft/appid/10554....

Python+Django+SAE系列教程1-----Python环境和基本语法

Python+Django+SAE系列教程1-----Python环境和基本语法
  • hemeng
  • hemeng
  • 2014年03月10日 23:40
  • 2629

Python+Django+SAE系列教程6-----本地配置Django

Python+Django+SAE系列教程6-----本地配置Django
  • hemeng
  • hemeng
  • 2014年04月21日 16:53
  • 2758

Python+Django+SAE系列教程10-----Django的模板

Python+Django+SAE系列教程10-----Django的模板
  • hemeng
  • hemeng
  • 2014年04月21日 17:32
  • 2272
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值