随笔 - 67  文章 - 12  评论 - 442  阅读 - 39万

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   Game_over  阅读(1307)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示