今天刚刚学习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 web
render = 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.debugerror
if __name__ == '__main__': app.run()
本文详细解析了Web.py框架中遇到XML访问异常的解决方案,包括修改模板名称和调整XML文件存放路径,以避免AttributeError:Notemplatenamed错误,并提供了XML访问的官方文档和示例代码。
431

被折叠的 条评论
为什么被折叠?



