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

今天刚刚学习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()


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

steely_chen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值