安裝
本人使用的是python3.6,因此會存在一點問題。不要用去github上下載包然後 python setup.py的方法,還是沒裝上。還會出現卸載不了的問題。關於卸載,可以參考這個解決方案 https://stackoverflow.com/questions/1550226/python-setup-py-uninstall ,可以卸載。
直接使用 pip install web.py==0.40.dev0 ,完美運行。
Hello World
首先寫入url的mapping
urls = ("/.*", "hello")
可以是多組元素,比如:
url = (
# '/(.*)','index'
'/', 'Index',
'/new', 'New'
)
其中,前面的正則,根據在地址欄中輸入的後綴,正則匹配,傳遞給對應的類。
class hello:
def GET(self):
return 'Hello, world!'
定義類
class hello:
def GET(self):
return 'Hello, world!'
這裏的類名和url中的是對應的。簡單地說,就是當正則匹配到時,就使用應用的類中的方法。
這裏也可以return一個網頁
return open('Index.html','rb').read().decode('utf-8')
因爲我這個網頁是中文的,所以要轉換一下。
完整代碼:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/5/9 16:44
# @Author : He Hangjiang
# @Site :
# @File : 01.py
# @Software: PyCharm
import web
url = (
'/(.*)','index'
)
app = web.application(url,globals())
class index:
def GET(self,name):
return open('Index.html','rb').read().decode('utf-8')
if __name__ == '__main__':
app.run()
在pycharm中運行,在瀏覽器中輸入127.0.0.1:8080,即可看到網頁。因爲此處是正則匹配所有字符,所以之後跟任何東西都是可以的,比如 http://127.0.0.1:8080/121341