web.py XML访问 例子详解 AttributeError: No template named index 异常解决方案

来源:互联网 发布:帮助画画的软件 编辑:程序博客网 时间:2024/06/14 20:10

今天刚刚学习web.py 框架,对于官方文档中 XML 访问的例子进行测试,发现不能运行,经常报如下错误

    raise AttributeError, "No template named " + name
AttributeError: No template named index


我看网上有很多朋友都出现过类似的问题,其中有以下两点大家要注意的(以官方的例子为例)。

1.  将 render.index(code) 中的index 换成response ,是因为案例中的xml文件是response.xml ,如果不修改index 也可以将response.xml 改成index.xml

2.  将 xml 文件放在templates 文件夹里面,请注意例子中的render = web.template.render("templates/",cache=False) 意思是说在templates下面找对应的template 文件 ,参数"templates/" 也可以指定具体的路径比如web.template.render('D:/work/templates/', cache=False) 这样会让程序运行更快,减少扫描整个目录时间与开销。

通过上面两种方法基本上可以解决 AttributeError: No template named index 异常 了

下面是 官方XML 访问的原文档


如何在web.py中提供XML访问?

如果需要为第三方应用收发数据,那么提供xml访问是很有必要的。

解法

根据要访问的xml文件(如response.xml)创建一个XML模板。如果XML中有变量,就使用相应的模板标签进行替换。下面是一个例子:

$def with (code)<?xml version="1.0"?><RequestNotification-Response><Status>$code</Status></RequestNotification-Response>

为了提供这个XML,需要创建一个单独的web.py程序(如response.py),它要包含下面的代码。注意:要用"web.header('Content-Type', 'text/xml')"来告知客户端--正在发送的是一个XML文件。

import webrender = web.template.render('templates/', cache=False)urls = (    '/(.*)', 'index')app = web.application(urls, globals())class index:    def GET(self, code):        web.header('Content-Type', 'text/xml')        return render.index(code)web.webapi.internalerror = web.debugerrorif __name__ == '__main__': app.run()


原创粉丝点击