webpy入門

來源:互聯網
上載者:User

標籤: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入門

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.