Python——Web.py詳解

时间:2022-07-04 10:41:21

  ubuntu安裝Web.py

 sudo pip install web.py

  測試代碼:

 import web

 urls = (
'/(.*)','hello'
)
app = web.application(urls,globals()) class hello:
def GET(self,name):
if not name:
name = 'world'
return 'hello,'+name+'!' if __name__=='__main__':
app.run()

类似于flask模板,这里也可以使用文件读写返回html内容:

 import web

 urls = (
'/(.*)','hello'
)
app = web.application(urls,globals()) class hello:
def GET(self,name):
return open(r'index.html','r').read() if __name__=='__main__':
app.run()

  URL映射:

      完全匹配: /index

      模糊匹配  /post/\d+

      带组匹配     /post/(\d+)

 import web

 urls = (
'/blog/\d+','blog',
'/index','index',
'/(.*)','hello',
)
app = web.application(urls,globals()) class index:
def GET(self):
return 'index' class blog:
def GET(self):
return 'blog' class hello:
def GET(self,name):
return 'hello' if __name__=='__main__':
app.run()

  请求处理:

    请求参数获取 :  web.input()

       hello.html源码:

 <!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<title>User Login</title>
</head> <body>
<div>
<h6>User Login</h6>
</div>
<form action="/blog/123" method="POST">
<h6>用戶名:</h6>
<input type="text" name="username"><br>
<h6>密碼:</h6>
<input type="password" name="password"><br>
<input type="submit" name="submit"><br>
</form>
</body>
</html>

    app.py源码:

 import web

 urls = (
'/blog/\d+','blog',
'/index','index',
'/(.*)','hello',
)
app = web.application(urls,globals()) class index:
def GET(self):
r = web.input()
return r class blog:
def POST(self):
r = web.input()
return r class hello:
def GET(self,name):
return open(r'hello.html','r').read() if __name__=='__main__':
app.run()

    运行结果:

         Python——Web.py詳解

              Python——Web.py詳解

              Python——Web.py詳解

   请求头获取    :  web.ctx.env

      app.py代码如下,hello.html代码如上相同

 import web

 urls = (
'/blog/\d+','blog',
'/index','index',
'/(.*)','hello',
)
app = web.application(urls,globals()) class index:
def GET(self):
return web.ctx.env class blog:
def POST(self):
r = web.input()
return r class hello:
def GET(self,name):
return open(r'hello.html','r').read() if __name__=='__main__':
app.run()

          运行结果:   Python——Web.py詳解     响应处理:

     模板文件读取:render.index("参数")

          在py文件同目录下要创建templates文件夹,存放模板。 

          index是指定模板的名称,参数是html中是所需参数。         

 import web

 render = web.template.render("templates")

 urls = (
'/blog/\d+','blog',
'/index','index',
'/(.*)','hello',
)
app = web.application(urls,globals()) class hello:
def GET(self,name):
return render.hello() if __name__=='__main__':
app.run()

         采用模板就可以不用之前所用的open(r'hello.html','r').read()了。

    结果数据获取:model.select("sql")

        参考我之前的文章http://www.cnblogs.com/LexMoon/p/Flask_6.html

    URL跳转       :web.seeother("/")    

 import web 

 urls = (
'/(.*)','hello',
)
app = web.application(urls,globals()) class hello:
def GET(self,name):
return web.seeother('http://www.cnblogs.com/LexMoon/') if __name__=='__main__':
app.run()