1.web.py简介
一个非常轻量级的web开发框架,简单而功能强大
使用Python语言开发web程序
2.web.py的安装
web.py的官网 www.webpy.org,上面有相应的文档和安装的相关步骤
首先得安装python,目前web.py只支持pythonw2.7x版本,不支持python3.x版本
可以使用python的包管理工具pip来安装web.py,进行命令行,键入命令pip install web.py即可成功安装web.py
3. web.py的测试
进行官网 www.webpy.org,将其给出的测试代码保存到本地,假设命令为hello.py
-
1 import web 2 urls =( 3 '/(.*)','hello' 4 ) 5 app = web.application(urls, globals()) 6 class hello: 7 def GET(self, name): 8 if not name: 9 name ='World' 10 return'Hello, '+ name +'!' 11 if __name__ =="__main__": 12 app.run()
运行这段代码
python hello.py
4. web的开发基础
WEB开发需要掌握 HTML CSS JS的基础知识
下面开始写第一个demo程序
import web urls =( '/(.*)','hello' ) app = web.application(urls, globals()) class hello: def GET(self, name): file = open('Welcome to web.py! (web.py).html','r') return file.read() if __name__ =="__main__": app.run()
效果如下图
5. URL映射
url完全匹配 /index
url模糊匹配 /post/\d+
url带组匹配 /post/(\d+)
1 import web 2 urls =( 3 '/index','index', 4 '/blog/\d+','blog', 5 '/(.*)','hello' 6 ) 7 app = web.application(urls, globals()) 8 class index: 9 def GET(self): 10 return"index" 11 class blog: 12 def GET(self): 13 return'blog' 14 class hello: 15 def GET(self, name ): 16 if name =="": 17 name ='world' 18 return'hello,'+name 19 if __name__ =="__main__": 20 app.run()
效果
6.请求的处理
请求参数的获取 web.input()
请求头获取 web.ctx.env
import web urls =( '/index','index', '/blog/\d+','blog', '/(.*)','hello' ) app = web.application(urls, globals()) class index: def GET(self): query = web.input() return query class blog: def POST(self): return web.input() def GET(self): return web.ctx.env class hello: def GET(self, name ): return open('1.html','r').read() if __name__ =="__main__": app.run()
效果
7.响应处理
1 import web 2 import MySQLdb 3 import MySQLdb.cursors 4 5 render = web.template.render("templates") 6 7 8 urls = ( 9 '/article','article', 10 '/index','index', 11 '/blog/\d+','blog', 12 '/(.*)','hello' 13 ) 14 app = web.application(urls, globals()) 15 16 class index: 17 def GET(self): 18 return web.seeother("http://www.baidu.com") 19 class blog: 20 def POST(self): 21 return web.input() 22 def GET(self): 23 return web.ctx.env 24 class hello: 25 def GET(self, name ): 26 return render.hello2(name) 27 class article: 28 def GET(self): 29 conn = MySQLdb.Connect(host="localhost",port=3306,user='root',passwd='123456',db='test') 30 cur=conn.cursor() 31 cur.execute('select * from articles') 32 r = cur.fetchall() 33 print cur.rowcount 34 35 cur.close() 36 conn.close() 37 return render.article(r) 38 39 if __name__ == "__main__": 40 app.run()
更多资料可参考http://webpy.org/