前面我们介绍了web.py是如何处理请求的,这篇我们介绍如何处理响应。响应一般就是给客户端一些数据,数据可能是一个网页,也可能是一些json数据,或者是跳转到一些其他地方,例如强制重定向。
1.响应处理有三种方式
1) 模板文件读取:render.index("参数")
2) 来自数据库查询: model.select("sql语句")
3) 重定向,例如你输入baidu.com,会重定向跳转到https://www.baidu.com
2 看看模本实现
1)把前面的123.html改成hello2.html,内容如下
<html>
<head>
<title>hello 123</title>
</head>
<body>
<h1>POST</h1>
<form action="/blog/123" method="POST">
<input type="text" name="id" value=""/>
<input type="password" name="password" value=""/>
<input type="submit" value="submit">
</form>
</body>
</html>
hello.py放在桌面上,然后在桌面创建一个templates的文件夹,把hello2.html放到templates文件夹里面。
2)hello.py修改后,如下
import web
render = web.template.render('templates')
urls = (
'/index', 'index',
'/blog/\d+', 'blog',
'/(.*)', 'hello'
)
app = web.application(urls, globals())
class hello:
def GET(self, name):
return render.hello2()
class index:
def GET(self):
query = web.input()
return query
class blog:
def POST(self):
data = web.input()
return data
def GET(self):
# get the request head
return web.ctx.env
if __name__ == "__main__":
app.run()
这里做了两处修改,下图红圈标记出来。
从上面演示效果来看,这个render和open方法差不多,但是网页通过模本的响应方式更高效和方便。例如,实际开发web的时候,搜索一个结果显示搜索结果页,其实都是调用模板来处理响应的,模板是一样的,只是数据不同。
3 实现URL跳转
就是在得到用户发送请求的时候,我们有时候需要把页面给跳转其他页面。例如访问127.0.0.1:8080/index,要求跳转到百度首页,我们这样来实现。
先把hello.py修改下
import web
render = web.template.render('templates')
urls = (
'/index', 'index',
'/blog/\d+', 'blog',
'/(.*)', 'hello'
)
app = web.application(urls, globals())
class hello:
def GET(self, name):
return render.hello2()
class index:
def GET(self):
query = web.input()
return web.seeother("https://www.baidu.com")
class blog:
def POST(self):
data = web.input()
return data
def GET(self):
# get the request head
return web.ctx.env
if __name__ == "__main__":
app.run()
只要浏览器地址栏输入127.0.0.1:8080/index,回车就会跳转到百度首页。