教你如何用幾行Python代碼編寫出一個簡易Web服務(wù)器
python的庫很豐富,只需要幾行代碼就能編寫出一個簡易 web 服務(wù)器,可以讓我們快速測試python腳本。
我們這里實現(xiàn)的只是一個簡易的 web 服務(wù)器,用在自己家軟路由上還是可以的,如果你需要功能更豐富以及性能更好的web服務(wù)器,請用 apache、nginx 等專業(yè)軟件。
在以前的文章中我們學(xué)習(xí)過python數(shù)據(jù)的持久化,那這里我們就提供一個web界面來進(jìn)行數(shù)據(jù)的持久化和更新操作。
一、編寫web服務(wù)器
使用 http.server 標(biāo)準(zhǔn)庫只需要幾行代碼就可以啟動一個web服務(wù)器了,如下代碼(要用python3,python2沒有http.server庫):
import os
from http.server import HTTPServer, CGIHTTPRequestHandler
webdir="/var/www"
os.chdir(webdir)
HTTPServer(("192.168.56.2", 8080), CGIHTTPRequestHandler).serve_forever()
用python3執(zhí)行以上代碼就會啟動一個監(jiān)聽192.168.56.2:8080地址的web服務(wù)器了,在瀏覽器地址欄輸入 http://192.168.56.2:8080/,如果web根目錄下有index.html文件就會顯示此文件,如果沒有就會默認(rèn)顯示根目錄結(jié)構(gòu),如下圖:
web根目錄結(jié)構(gòu)
二、編寫展示數(shù)據(jù)腳本
cgi腳本要放在web根目錄下的cgi-bin目錄下,如果沒有這個目錄請先創(chuàng)建它,然后在cgi-bin目錄下創(chuàng)建一個student.py文件,內(nèi)容如下:
#!/usr/bin/env python3
import pickle
import os
student_keys = ("name", "gender", "age", "score")
if os.path.exists("student.data"):
with open("student.data", "rb") as file:
student = pickle.load(file)
student = student or {}
else:
student = {}
if not student:
student = dict.fromkeys(student_keys, "")
header = "Content-Type: text/html\n"
content = """
<html>
<body>
<form action="/cgi-bin/update.py" method="POST">
<table>
<tr>
<td>name: </td>
<td><input name="name" value="{name}"/></td>
</tr>
<tr>
<td>gender:</td>
<td><input name="gender" value="{gender}"/></td>
<tr>
<tr>
<td>age: </td>
<td><input name="age" value="{age}"/></td>
</tr>
<tr>
<td>score: </td>
<td><input name="score" value="{score}"/></td>
</tr>
<tr>
<td style="padding-top: 10px" align="center" colspan="2">
<button type="submit">Submit</button>
</td>
</tr>
</table>
</form>
</body>
</html>
"""
print(header + content.format(**student))
name: | |
gender: | |
age: | |
score: | |
Submit |
在瀏覽器地址欄中輸入:
http://192.168.56.2:8080/cgi-bin/student.py
第一次加載時由于數(shù)據(jù)是空的,所以顯示為空,如下圖:
第一次加載顯示數(shù)據(jù)為空
三、編寫更新數(shù)據(jù)腳本
同樣在cgi-bin目錄下創(chuàng)建一個update.py文件,內(nèi)容如下:
#!/usr/bin/env python3
import os
import cgi
import pickle
student_keys = ("name", "gender", "age", "score")
if os.path.exists("student.data"):
with open("student.data", "rb") as file:
student = pickle.load(file)
student = student or {}
else:
student = {}
if not student:
student = dict.fromkeys(student_keys, "")
form = cgi.FieldStorage()
for key in student_keys:
if key in form and form[key].value:
student[key] = form[key].value
with open("student.data", "wb") as file:
pickle.dump(student, file)
header = "Content-Type: text/html\n"
content = """
<html>
<body>
<h1>update successfully, will skip to display page: <span id="count_down">3</span></h1>
<script>
var count = 3
timer_id = setInterval(function(){
count = count -1
if(count == 0) {
clearInterval(timer_id)
location.href="/cgi-bin/student.py"
} else {
document.getElementById("count_down").innerHTML = "" + count
}
},1000)
</script>
</body>
</html>
"""
print(header + content)
四:驗證更新功能
編寫完更新腳本后,在第二步中的輸入框內(nèi)輸入信息,如下圖:
輸入各項信息
然后點(diǎn)擊提交按鈕,就會跳轉(zhuǎn)到更新成功頁面,如下圖:
更新成功頁面
倒計時3秒后會跳轉(zhuǎn)到展示頁,這時就會有數(shù)據(jù)了,然后我們修改數(shù)據(jù),把score 修改為100,如下圖:
修改 score 為 100
點(diǎn)擊提交按鈕等再次跳轉(zhuǎn)到展示頁時可以看到 score 已經(jīng)更新為100了。
是不是很簡單,你學(xué)會了嗎?