web.py 數(shù)據(jù)庫操作

2022-04-24 18:21 更新

注意: 在你開始使用數(shù)據(jù)庫之前,確保你已經(jīng)安裝了合適的數(shù)據(jù)庫訪問庫。比如對于MySQL數(shù)據(jù)庫,使用 pymysql,對于Postgres數(shù)據(jù)庫使用psycopg2。

首先你需要創(chuàng)建一個數(shù)據(jù)庫對象。

db = web.database(dbn='postgres', user='username', pw='password', db='dbname')

(根據(jù)需要修改這里 – 尤其是username 、 password 、 dbname – 。 MySQL用戶還需要把 dbn 定義改為 mysql。)

這就是所有你需要做的 – web.py將會自動處理與數(shù)據(jù)庫的連接和斷開。

使用的的數(shù)據(jù)庫引擎管理工具,在你的庫中創(chuàng)建一個簡單的表:

CREATE TABLE todo (
  id serial primary key,
  title text,
  created timestamp default now(),
  done boolean default 'f'    );

然后初始化行:

INSERT INTO todo (title) VALUES ('Learn web.py'); 我們回來繼續(xù)編輯 code.py ,把 index.GET 改成下面的樣子,替換整個函數(shù):

    def GET(self):
        todos = db.select('todo')
        return render.index(todos)

然后把URL列表改回來,只保留 /:

'/', 'index',

像這樣編輯并替換 index.html 的全部內(nèi)容:

$def with (todos)
<ul>
$for todo in todos:
    <li id="t$todo.id">$todo.title</li>
</ul>

再訪問你的網(wǎng)站,然后你可以看到你的todo item: “Learn web.py”。恭喜你!你已經(jīng)完整地寫好了一個可以從數(shù)據(jù)庫讀取數(shù)據(jù)的程序。現(xiàn)在讓我們同樣再寫一個可以把數(shù)據(jù)寫入數(shù)據(jù)庫的程序。

在 index.html尾部添加:

<form method="post" action="add">
<p><input type="text" name="title" /> <input type="submit" value="Add" /></p>
</form>

然后把你的URL列表改為:

'/', 'index',
'/add', 'add'

(你必須要非常小心那些逗號。如果你省略他們,Python會把所有字符串連接起來,變成 '/index/addadd')

現(xiàn)在添加另一個類:

class add:
    def POST(self):
        i = web.input()
        n = db.insert('todo', title=i.title)
        raise web.seeother('/')

(注意現(xiàn)在我們正在使用 POST)

web.input 可以讓你訪問用戶通過form提交的任何數(shù)據(jù)。

注意: 如果要訪問多個相同名字的字段,請使用list的格式(比如:一串name=”name”的多選框):

post_data=web.input(name=[])

db.insert 把數(shù)據(jù)插入數(shù)據(jù)表 todo ,然后把新的行號返回給你。 seeother 把用戶重定向到指定的URL。

一些快速補(bǔ)充說明: db.update 與 db.insert 差不多,除了它返回的行號是直接從sql語句里面提取的(WHERE ID=2)。

web.input、 db.query已經(jīng)其他web.py中的函數(shù)返回”Storage objects”,這些東西就像字典,你除了可以 d['foo']之外,你還可以 d.foo。這可以讓代碼更加干凈。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號