webpy入門
工作環境中需要經常生產和測試服務器,機房一直很混亂,因此萌生了開發一個簡單方便的服務器管理系統(說的好高大上,其實就是個可以獲取服務器信息的小web應用)。之所以選擇webpy,正式因為它夠簡單,尤其是對於我這種python新人來說。它是一款輕量級的python web開發框架,對於個人開發小應用來說很適合。
webpy install
下載:wget http://webpy.org/static/web.py-0.37.tar.gz
安裝:python setup.py install
webpy 'hello world'
可以參考webpy的官方文檔:http://webpy.org/docs/0.3/tutorial
hello, world如下:
import web urls = ( '/', 'index' ) class index: def GET(self): return "Hello, world!" if __name__ == "__main__": app = web.application(urls, globals()) app.run()
在webpy中,url請求的映射在urls元組中,如上圖中GET ip:port/,會直接調用index類的GET方法,返回字符串'hello, world!';
class index中包含了一個GET方法,用來處理與index相應的url的GET請求的;
在主函數中,只需要創建一個application對象,運行就可以開啟一個簡單的web應用,默認的地址為:127.0.0.1:8080
GET && POST
web包含兩種方法:GET和POST
對於GET,可以采用:
class index: def GET(self): return "Hello, world!"
而,對於POST,采用:
class index: def POST(self): data = web.input(name=None) return "Hello, " + data.name + "!"
html模板
在webpy中,一般采用templates來存放html頁面文件。大概的訪問方式如下:
urls = ( '/img', 'image' ) render = web.template.render('templates') class image: def GET(self): return render.image()
urls中定義了url映射,訪問ip:port/img會直接條用class image來處理;
web.template.render(path)是用來指定存放html的目錄,上面指定了html的指定存放位置位於當前文件夾下的templates文件下;
返回的render.image()表示在render所指定的目錄下尋找image.html文件並作為返回結果。
class show: def GET(self): return render.show('hello world!')
$def with(str) <html> <body> $for i in range(5): <h1>$str</h1> <body> </html>
show類是用來展示字符串'hello world!',下面的html為show.html,webpy支持模板,支持參數以$def with()開始作為函數的開始;
在html中可以使用python語句,但語句前需要添加$,在上面的html中str會在頁面上打印5次。
靜態文件
在webpy中,提供了默認的靜態文件的訪問方式
- webpy作為服務器時,在當前目錄下建立static目錄,webpy會自動在該目錄下尋找靜態文件
- 在 Apache 中可以使用 Alias 指令,在處理 web.py 之前將請求映射到指定的目錄。
webpy db
在webpy中提供了數據庫訪問的API,其實從源碼中可以看出來是對MySQLdb的封裝,但為了方便起見用起來還是可以的。
db = web.database(dbn='mysql', db='test', user='root', pw='123123') def new_post(title, content): db.insert('news', title=title, content=content, posted_on=datetime.datetime.utcnow()) def get_post(id): try: return db.select('news', where='id=$id', vars=locals())[0] except IndexError: return None def get_posts(): return db.select('news', order = 'id DESC') def del_post(id): db.delete('news', where = 'id = $id', vars = locals()) def update_post(id, title, content): db.update('news', where='id = $id', vars=locals(), title=title, content=content)
webpy也支持事務:
import web db = web.database(dbn="postgres", db="webpy", user="foo", pw="") t = db.transaction() try: db.insert('person', name='foo') db.insert('person', name='bar') except: t.rollback() raise else: t.commit()
![]()
本作品采用 知識共享署名-非商業性使用-相同方式共享 3.0 未本地化版本許可協議進行許可。歡迎轉載,請注明出處:
轉載自: cococo點點 http://www.cnblogs.com/coder2012