您的位置:首页 > 编程语言 > Python开发

Python Web开发介绍(二) -Web.py模板使用中的问题

2013-01-23 19:22 766 查看
Web.py的模板系统很重要,
可以说是必备武器.

承接上一篇文档的代码.

按照web.py的官方文档说明开始做吧:

1.
在test目录下建立一个tmplt文件夹;

2.
在tmplt文件夹下建立一个模板文件t1.html

3.
code2.py里增加代码

……

render = web.template.render('/tmplt/')

…..

class hello:

def GET(self):

return render.t1(todos)

#return "Hello, world!"
这句话注掉了,我们开始用模板了

……

4.
重启一下Apache(必备步骤,改动了py文件后,就要重启一下Apache,以使改动生效)

5.
地址栏里输入网址http://127.0.0.1/test2;

结果返回了HTTP 500 内部服务器错误. 查看C:\Program Files\Apache Software Foundation\Apache2.2\logs\error.log, 错误信息如下

Traceback (most recent call last):

File :\\Python27\\lib\\site-packages\\web\\application.py", line 239, in process return self.handle()

File :\\Python27\\lib\\site-packages\\web\\application.py", line 230, in handle return self._delegate(, self.fvars, args)

File :\\Python27\\lib\\site-packages\\web\\application.py", line 462, in _delegate return handle_class(cls)

File :\\Python27\\lib\\site-packages\\web\\application.py", line 438, in handle_class return tocall(*args)

File "D:/SW_Code/test/code2.py", line 45, in GET return render.(todos)

File :\\Python27\\lib\\site-packages\\web\\template.py", line 1016, in __getattr__ = self._template(name)

File :\\Python27\\lib\\site-packages\\web\\template.py", line 1010, in _template self._cache[name] = self._load_template(name)

File :\\Python27\\lib\\site-packages\\web\\template.py", line 1000, in _load_template raise AttributeError, "No template named + name

AttributeError: No template named t1

错误是AttributeError: No template named t1,
貌似是说模板文件没找到.

网上搜索了一遍,
确认问题在于模板的路径不对. web.template.render('/tmplt/')这样写的话,
貌似Apache只会在C:\Program Files\Apache Software Foundation\Apache2.2这个所谓的网站服务器根目录下面去找tmplt文件夹,而不会自动使用相对路径去我们的代码文件夹里找.

所以我们必须给出这个tmplt的的全路径.用下面的代码,
可以不必在程序代码里写死路径:

……

root_dir=os.path.dirname(__file__)

render = web.template.render(root_dir+'/tmplt/')

……

这样的话,在初始化render的时候就会去我们的代码文件夹下找模板文件夹目录了.
重启Apache后,网站正常运行了.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: