Python Web编程(四)

经过前面的学习,是不是很心动,要做一个真正的网页看看吗?

呵呵,不要着急,还有一项很重要的--Django模板系统没有接触呢。

在实际应用中,很少会直接在Python方法中返回HTML页面,这样做就会造成页面和服务的紧耦合。

Django的模板系统可以很好的解决这个问题。

好了,首先需要做的就是件一个目录,专门存放模板。我的目录是D:/PythonWeb/test1/templates。

还需要在settings.py里面配置模版路径:
TEMPLATE_DIRS = (
    "D:/PythonWeb/test1/templates"
)

current_datetime.html:

<html><meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<body>It is right now {{ current_date }}.</body></html>

在urls.py中加入下面内容:

(r'^nowtime/$', 'test1.helloworld.current_datetime'),

在helloworld.py中应该有如下内容:

from django.http import HttpResponse
from django.template import Template, Context
from django.template.loader import get_template
import datetime

def current_datetime(request):
    now = datetime.datetime.now()
    t = get_template('current_datetime.html')
    html = t.render(Context({'current_date': now}))
    return HttpResponse(html)

好了,http://localhost/nowtime/,试一下吧。

可以了吧,那么注意了,上面的方法需要引入三个模块,有没有更简便的办法呢?

答案是有的。

下面的代码可以实现相同的功能:

from django.shortcuts import render_to_response
import datetime 
def current_datetime(request):
    now = datetime.datetime.now()
    return render_to_response('current_datetime.html', {'current_date': now})

 

简单吧,我们试一下给上节的hour_offset方法创建模版。

创建hour_offset.html如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> 
<html lang="en"> 
<head> 
    <title>Future time</title> 
</head> 
<body> 
    <h1>My helpful timestamp site</h1> 
    <p>In {{ hour_offset }} hour(s), it will be {{ next_time }}.</p> 
 
    <hr> 
    <p>Thanks for visiting my site.</p> 
</body> 
</html> 

然后修改test.py:

from django.http import HttpResponse
from django.template import Template, Context
from django.template.loader import get_template
import datetime
def hour_offset(request, plus_or_minus, offset):
    offset = int(offset)
    t = get_template('hour_offset.html')
    if offset == 1:
        hours = 'hour'
    else:
        hours = 'hours'
    if plus_or_minus == 'plus':
        dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
    else:
        dt = datetime.datetime.now() - datetime.timedelta(hours=offset)
    html = t.render(Context({'hour_offset': offset,'next_time': dt}))
    return HttpResponse(html)

 好了,大功告成,http://localhost/now/plus21hours/

下一节继续木板的一些特性。

posted on 2007-09-12 21:36  Game_over  阅读(1303)  评论(0编辑  收藏  举报