工作環(huán)境中需要經(jīng)常生產(chǎn)和測試服務(wù)器,機房一直很混亂,因此萌生了開(kāi)發(fā)一個(gè)簡(jiǎn)單方便的服務(wù)器管理系統(說(shuō)的好高大上,其實(shí)就是個(gè)可以獲取服務(wù)器信息的小web應用)。之所以選擇webpy,正式因為它夠簡(jiǎn)單,尤其是對于我這種python新人來(lái)說(shuō)。它是一款輕量級的python web開(kāi)發(fā)框架,對于個(gè)人開(kāi)發(fā)小應用來(lái)說(shuō)很適合。
下載:wget http://webpy.org/static/web.py-0.37.tar.gz
安裝:python setup.py install
可以參考webpy的官方文檔:http://webpy.org/docs/0.3/tutorial
hello, world如下:
import weburls = ( '/', '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/,會(huì )直接調用index類(lèi)的GET方法,返回字符串'hello, world!';
class index中包含了一個(gè)GET方法,用來(lái)處理與index相應的url的GET請求的;
在主函數中,只需要創(chuàng )建一個(gè)application對象,運行就可以開(kāi)啟一個(gè)簡(jiǎn)單的web應用,默認的地址為:127.0.0.1:8080
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 + "!"
在webpy中,一般采用templates來(lái)存放html頁(yè)面文件。大概的訪(fǎng)問(wèn)方式如下:
urls = ( '/img', 'image')render = web.template.render('templates')class image: def GET(self): return render.image()
urls中定義了url映射,訪(fǎng)問(wèn)ip:port/img會(huì )直接條用class image來(lái)處理;
web.template.render(path)是用來(lái)指定存放html的目錄,上面指定了html的指定存放位置位于當前文件夾下的templates文件下;
返回的render.image()表示在render所指定的目錄下尋找image.html文件并作為返回結果。
class show: def GET(self): return render.show('hello world!')
show類(lèi)是用來(lái)展示字符串'hello world!',下面的html為show.html,webpy支持模板,支持參數以$def with()開(kāi)始作為函數的開(kāi)始;
在html中可以使用python語(yǔ)句,但語(yǔ)句前需要添加$,在上面的html中str會(huì )在頁(yè)面上打印5次。
靜態(tài)文件
在webpy中,提供了默認的靜態(tài)文件的訪(fǎng)問(wèn)方式

在webpy中提供了數據庫訪(fǎng)問(wèn)的API,其實(shí)從源碼中可以看出來(lái)是對MySQLdb的封裝,但為了方便起見(jiàn)用起來(lái)還是可以的。
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 Nonedef 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也支持事務(wù):
import webdb = 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() raiseelse: t.commit()
本作品采用知識共享署名-非商業(yè)性使用-相同方式共享 3.0 未本地化版本許可協(xié)議進(jìn)行許可。歡迎轉載,請注明出處:
轉載自:cococo點(diǎn)點(diǎn) http://www.cnblogs.com/coder2012
聯(lián)系客服