python web py入门-6-响应处理(上)

       前面我们介绍了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,回车就会跳转到百度首页。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值