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/。
下一节继续木板的一些特性。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .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语句:使用策略模式优化代码结构