標籤:io os sp 檔案 on 代碼 bs html ef
webpy_tutorial
import weburls = ( ‘/‘, ‘index‘ )
這行表示我們要URL/(首頁)被一個叫index的類處理
建立一個列舉這些url的application
app = web.application(urls, globals())
現在來寫index類,首先定義GET或者POST兩個方法
class index: def GET(self): return "hello, world"
有人用GET發出請求時,GET函數會被web.py調用
最後開始運行代碼:
if __name__ == "__main__": app = web.application(urls, globals()) app.run()
完整的代碼儲存為server.py:
import weburls = ( ‘/‘, ‘index‘)class index: def GET(self): return "Hello, world!"if __name__ == "__main__": app = web.application(urls, globals()) app.run()
命令列輸入python server.py就可以運行這個簡單的伺服器,也可以指定連接埠號碼:
python server.py 1234
模板
給模板建立一個目錄,命名為templates,在該目錄下建立一個hello.html檔案,內容如下:
<em>Hello</em>, world!
然後在server.py的第一行下面添加:
render = web.py.template.render(‘templates/‘)
這會告訴web.py到模板目錄去尋找模板,然後修改index.GET:
return render.hello()
這裡hello是剛才建立的模板名字hello.html
修改之後運行server.py,訪問網站將會顯示粗體的‘hello,world!‘
接下來可以再模板中增加一些互動功能,修改hello.html:
$def with (name)$if name: I just wanted to say <em>hello</em> to $name.$else: <em>Hello</em>, world!
這裡的模板代碼與python代碼類似,程式碼片段之前都有$
然後修改server.py中的index.GET:
def GET(self): name = ‘Alice‘ return render.hello(name)
這裡name會作為參數傳入到模板裡面,正如模板檔案的開頭要求傳入的參數
現在運行server.py後訪問將會顯示I just wanted to say hello to Alice. ,當然如果參數是Null 字元串將會顯示Hello, world!
如果讓使用者輸入自己的名字,修改index.GET:
i = web.input(name=None)return render.index(i.name)
在訪問的地址後面加上/?name=Alice就可以通過GET的形式訪問,將會顯示I just wanted to say hello to Joe.
如果覺得URL後面跟著?看起來不好看,可以修改URL的配置:
‘/(.*)‘, ‘index‘
然後修改URL配置:
def GET(self, name): return render.hello(name)
這樣對於/後面的任何字串都可以進行處理,作為name參數進行傳遞
webpy入門