python-web.py 入门介绍

内容来源:webpy.org

介绍:

1、python中web.py 是一个轻量级Python web框架,它简单而且功能强大。web.py是一个开源项目。

2、安装很简单:pip install web.py

3、URL处理

例:hello word

import web
#模糊匹配 urls = ("/.*", "hello") app = web.application(urls, globals()) class hello: def GET(self):
#给页面返回值(响应结果) return 'Hello, world!' if __name__ == "__main__": app.run()

#测试:
请求地址:
http://localhost:8080/
请求方式GET

总结:以上是一个最简单的应用web.py的例子,介绍了一种URL处理,并且返回值直接是return 一个字符串的简单形式,下面详细进行说明web.py的强大之处:

1、URL处理支持三种形式:
urls = (
#精确匹配
'/selectDB', 'selectDb',
# 精确匹配
'/index', 'index',
# 模糊的不带组的
'/blog/d+', 'blog',
# 带组的模糊匹配
'/(.*)', 'hello'
)

这个类名为上面的URL:'/blog/d+', 'blog',相关联的
class blog(object):
    def GET(self):
print 'GET'
query = web.input()
return query

def POST(self):
print "Post"
query = web.input()
print '用户名:', query['username'], '密码:', query['password']
return query
上面的请求支持GET和POST

例:模拟POST请求:需要写一个form表单提交
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hello</title>
</head>
<body>
<h1>POST</h1>
<form action="/blog/123" method="post">
用户名:<input type="text" id="username" name="username" value=""/>
密 码:<input type="password" id="password" name="password" value=""/><br>
<input type="submit" value="submit" />
</form>
</body>
</html>
总结:此部分重点需要了解web.input()的使用,用于接收请求的参数(POST/GET),

2、下面再继续学习从数据库查询出结果,返回给页面的例子:
import web
import MySQLdb
print "Web.py 练习"
urls = (

'/selectDB', 'selectDb',

)
app = web.application(urls, globals())
# 响应使用模板的方式
render = web.template.render('templates')
class selectDb(object):

def GET(self):
conn = MySQLdb.connect(
host='localhost',
port=3306,
user='root',
passwd='root',
db='cf_sjjy',
charset='utf8'
)
cursor = conn.cursor()
cursor.execute("select CertId,Name from zhengxin_hit_rules")
rs = cursor.fetchall()
cursor.close()
conn.close()
print rs
return render.article(rs)

if __name__ == "__main__":

app.run()

HTML页面如下:
$def with(rs)
<html lang="en">
<head>
<meta charset="UTF-8">
<title>数据库查询</title>
</head>
<body>
<h1>数据库查询</h1>
<ul>
$for v in rs:
<li>$v[0] => $v[1]</li>
</ul>
</body>
</html>
总结:这个例子说明了如何把结果list返回到界面展示,使用到了模板的应用,需要创建一个模板文件夹templates里面创建一个article.html

内容如上,通过return render.article(rs)给页面传值,页面最上面$def with(rs)接收值,然后通过for循环取值。

$for v in rs:

<li>$v[0] => $v[1]</li>

可以掌握到的内容:
1、web.py大体架构和概念
2、web.py的url处理机制
3、发送请求POST/GET
4、数据库操作mysql
5、模板的使用(article.html)
5、响应值传递,解析和展示处理(

return render.article(rs)

$def with(rs)、
$for v in rs:
    <li>$v[0] =>  $v[1]</li>
)主要是这三个的理解。



原文地址:https://www.cnblogs.com/wenhongyu/p/7207188.html