Web.py學習報告
Web.py學習報告
Web.py是一個輕量型Python web架構,但是之前沒學過Python,所以先在網上簡單的了解了這門語言,發現Python可以很方便的使用c語言函數和c++庫,使用起來也很靈活,今後應該會多接觸接觸這門語言。了解了這門語言之後,參考了web.py官網文檔,看了一些入門教程,然後就跟著官網的幾個例子進行學習。
系統: ubuntu
工具:VIM
例子:Todo list
主要是照著教程跟著寫和調試,理解數據的傳輸流程
結構如下:,
/schema.sql
/templates:
/templates/base.html
/templates/index.html
/model.py
/todo.py
/schema.sql
CREATE TABLE todo (
id INT AUTO_INCREMENT,
title TEXT,
primary key (id)
);
這是創建todo表,主鍵是int類型的id,還有個title是text類型,我用的是mysql,首先要進入mysql,mysql -u root -p,輸入密碼進入,建立數據庫todo,create database todo;,然後建立數據表也叫todo,方式是執行schema.sql,在mysql下,use todo;source schema.sql;,提示ok,然後desc todo;
mysql> desc todo;
+-------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| title | text | YES | | NULL | |
+-------+---------+------+-----+---------+----------------+
2 rows in set (0.01 sec)
這還是空表,查看表內容,我們用select * from todo;查看
/model.py
import web
db = web.database(dbn=‘mysql‘, db=‘todo‘, user=‘root‘,pw=‘123456‘)
def get_todos():
return db.select(‘todo‘, order=‘id‘)
def new_todo(text):
db.insert(‘todo‘, title=text)
def del_todo(id):
db.delete(‘todo‘, where="id=$id", vars=locals())
model中定義了數據庫連接的方式,三個函數,各自功能很容易理解
/todo.py
""" Basic todo list using webpy 0.3 """
import web
import model
### Url mappings
urls = (
‘/‘, ‘Index‘,
‘/del/(\d+)‘, ‘Delete‘
)
### Templates
render = web.template.render(‘templates‘, base=‘base‘)
class Index:
form = web.form.Form(
web.form.Textbox(‘title‘, web.form.notnull,
description="I need to:"),
web.form.Button(‘Add todo‘),
)
def GET(self):
""" Show page """
todos = model.get_todos() #調用model方法
form = self.form()
return render.index(todos, form)#把todos和form傳入模板的index.html
def POST(self):
""" Add new entry """
form = self.form()
if not form.validates():#form校驗
todos = model.get_todos()
return render.index(todos, form)
model.new_todo(form.d.title)#把form文本框的內容添加到數據庫
raise web.seeother(‘/‘)#轉到‘/’下的頁面
class Delete:
def POST(self, id):
""" Delete based on ID """
id = int(id)
model.del_todo(id) #刪除id的title
raise web.seeother(‘/‘)#轉到index中的GET
if __name__ == ‘__main__‘:
app = web.application(urls, globals())
app.run()
urls定義了訪問不同路徑對應的處理類,render定義模板,Index中首先定義一個Form,一個文本框,一個按鈕,然後分別定義GET和POST方法
/templates/index.html
$def with (todos, form) #傳入todos,form
<table>
<tr>
<th>What to do ?</th>
<th></th>
</tr>
$for todo in todos: #循環顯示todo.title
<tr>
<td>$todo.title</td>
<td>
<form action="/del/$todo.id" method="post">
<input type="submit" value="Delete"/>
</form>
</td>
</tr>
</table>
<form action="" method="post">
$:form.render()
</form>
/templates/base.html
$def with (page)
<html>
<head>
<title>Todo list</title>
</head>
<body>
$:page
</body>
</html>
頁面都在body中顯示
運行python todo.py 8090
瀏覽器中打開:http://0.0.0.0:8090/
運行界面如圖:
Web.py學習報告