使用語言:python3.6
使用框架:web.py
1.安裝框架:
由于使用python3 ,所以在控制臺中使用以下命令進行安裝:
pip install web.py==0.40.dev0
2.hello world:
新建一個python文件,寫入如下代碼:
import web
urls = ( '/', 'index')
class index:
def GET(self):
return "Hello, world!"
if __name__ == "__main__":
app = web.application(urls, globals())
app.run()
運行代碼,在瀏覽器中輸入127.0.0.1:8080,可以看到Hello, world!字樣。
源碼解釋:
1.urls 元組中,第一個元素'/'是正則表達式,用來匹配url,第二個元素是接受請求的類名稱。
更改代碼舉例:
urls=('/test','result')
這句則意味著:訪問127.0.0.1:8080/test 就會調用result類。
2.index類中,只定義了一個GET方法可以返回一個句子:Hello, world!,GET方法用于請求網頁文本,注:瀏覽器默認請求方式即為get。
3.創(chuàng)建一個列舉這些url的application(不清楚這個是什么),然后運行一下run函數(shù)就可以運行了。
3.加個模板
在當前目錄下新建一個文件夾命名為templates,在templates文件夾下新建一個test_01.html文件。
寫入如下內容
$def with (name=None)
$if name:
I just wanted to say <em>hello</em> to $name.
$else:
<em>Hello</em>, world!
python 修改如下:
import web
render = web.template.render('templates/')
urls = ( '/', 'index')
class index:
def GET(self):
i = web.input(name=None)
return render.test_01(i.name)
if __name__ == "__main__":
app = web.application(urls, globals())
app.run()
運行代碼,在瀏覽器中輸入127.0.0.1:8080/?name=Bob,可以看到I just wanted to say hello to Bob.字樣。在瀏覽器中輸入127.0.0.1:8080,可以看到Hello, world!字樣。
源碼解釋:
html文件:
def with (表示從模板將從這后面取值)
$位于代碼段之前
python文件:
render = web.template.render('templates/')
告訴web.py到templates文件夾中查找模板。
i = web.input(name=None)
讓用戶自行輸入名字,并將名字賦給name。
return render.test_01(i.name)
返回templatems文件夾中test_01文件,并給其中的name賦予上一步用戶輸入的名字(上一步賦給了i中的name)。