码迷,mamicode.com
首页 > Web开发 > 详细

Django 笔记 动态URL

时间:2016-02-06 14:28:55      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:hello   动态   style   

之前我们做了hello的url转向,这是静态的,有些视图是动态的比如127.0.0.1:8000/articles/123 , book/345等。

让我们创建第三个视图来显示当前时间和加上时间偏差量的时间,设计是这样的: /time/plus/1/ 显示当前时

间+1个小时的页面 /time/plus/2/ 显示当前时间+2个小时的页面 /time/plus/3/ 显示当前时间+3个小时的

新手可能会考虑写不同的视图函数来处理每个时间偏差量

面向函数你可能会考虑

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),
)


但是我们不是呆子啊,程序员都是智商超过120的天才啊

来来跟我敲代码


Urls.py

from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls import patterns, include, url
from app01 import views as myapp
admin.autodiscover()
urlpatterns = [
   url(r‘^admin/‘, include(admin.site.urls)),
   url(r‘^$‘,myapp.index),
   url(r‘^hello/$‘,myapp.hello),
   url(r‘^time/plus/(\d{1,2})/$‘, myapp.hours_ahead),
   url(r‘^time/‘,myapp.current_datetime),

]


views.py


def hours_ahead(request,offset):
try:
        offset = int(offset)
except ValueError:
raise Http404()
#raise "404"
now = datetime.datetime.now()
    dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
    html = "<html><body>当前时间 %s </br> 时差%s小时, %s.</body></html>" % (now,offset, dt)
return HttpResponse(html)


技术分享

URL只匹配了2位plus后面,如果输入100那么将获取不到参数


技术分享




最后,很显然这些信息很多是敏感的,它暴露了你 Python 代码的内部结构以及 Django 配置,在 Internet 上

公开这信息是很愚蠢的。 不怀好意的人会尝试使用它攻击你的 Web 应用程序,做些下流之事。 因此,

Django 出错信息仅在 debug 模式下才会显现。 我们稍后 说明如何禁用 debug 模式。 现在,你只要知道

Django 服务器在你开启它时默认运行在 debug 模式就行了。 (听起来很熟悉? 页面没有发现错误,如前所

述,工作正常。)





本文出自 “于昊(Pcdog)的博客” 博客,请务必保留此出处http://433266.blog.51cto.com/423266/1741297

Django 笔记 动态URL

标签:hello   动态   style   

原文地址:http://433266.blog.51cto.com/423266/1741297

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!