python web py入门-6-响应处理(上)
来源:互联网 发布:淘宝美工在线布局 编辑:程序博客网 时间:2024/06/08 10:11
前面我们介绍了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 queryclass blog:def POST(self):data = web.input()return datadef GET(self): # get the request headreturn web.ctx.envif __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 datadef GET(self): # get the request headreturn web.ctx.envif __name__ == "__main__": app.run()只要浏览器地址栏输入127.0.0.1:8080/index,回车就会跳转到百度首页。
阅读全文
0 0
- python web py入门-6-响应处理(上)
- python web py入门-7-响应处理(下)
- python web py入门-4-请求处理(上)
- python web py入门-5-请求处理(下)
- python-web.py 开发入门
- python web py入门-1-web.py简介和安装
- python web py入门-1-web.py简介和安装
- python web py入门-3-URL映射
- 开发:web.py(上)
- Web.py 入门例程
- web.py数据库入门
- web.py入门纪要
- web.py数据库入门
- web.py入门
- web.py框架入门
- web.py处理url
- python web py入门-2-显示一个demo网页
- python 之web.py
- OVS+DPDK
- 在Mac上删除自己安装的Python
- Python_进程池
- azkaban2.5.0安装
- 函数式编程(1):高阶函数
- python web py入门-6-响应处理(上)
- 文章标题
- UVA
- 进程间通信
- express简单路由能力
- Android友盟新浪分享5.0以下版本报错SSLSocket
- 第十章 会话管理(一) 会话
- Gensim官方教程翻译(二)——语料库与向量空间(Corpora and Vector Spaces)
- Python基础学习-Django基础