工作環(huán)境中需要經(jīng)常生產(chǎn)和測試服務(wù)器,機(jī)房一直很混亂,因此萌生了開發(fā)一個簡單方便的服務(wù)器管理系統(tǒng)(說的好高大上,其實(shí)就是個可以獲取服務(wù)器信息的小web應(yīng)用)。之所以選擇webpy,正式因?yàn)樗鼔蚝唵危绕涫菍τ谖疫@種python新人來說。它是一款輕量級的python web開發(fā)框架,對于個人開發(fā)小應(yīng)用來說很適合。
下載: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/,會直接調(diào)用index類的GET方法,返回字符串'hello, world!';
class index中包含了一個GET方法,用來處理與index相應(yīng)的url的GET請求的;
在主函數(shù)中,只需要創(chuàng)建一個application對象,運(yùn)行就可以開啟一個簡單的web應(yīng)用,默認(rèn)的地址為: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來存放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的指定存放位置位于當(dāng)前文件夾下的templates文件下;
返回的render.image()表示在render所指定的目錄下尋找image.html文件并作為返回結(jié)果。
class show: def GET(self): return render.show('hello world!')
show類是用來展示字符串'hello world!',下面的html為show.html,webpy支持模板,支持參數(shù)以$def with()開始作為函數(shù)的開始;
在html中可以使用python語句,但語句前需要添加$,在上面的html中str會在頁面上打印5次。
靜態(tài)文件
在webpy中,提供了默認(rèn)的靜態(tài)文件的訪問方式
在webpy中提供了數(shù)據(jù)庫訪問的API,其實(shí)從源碼中可以看出來是對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 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)行許可。歡迎轉(zhuǎn)載,請注明出處:
轉(zhuǎn)載自:cococo點(diǎn)點(diǎn) http://www.cnblogs.com/coder2012