Writing data to a text or database using CGI
1. Turn on the CGI service
Python-m http.server--cgi port[Port Optional default is 8000]
update.py Code
#coding: UTF8
Import CGI
c = CGI. Fieldstorage () #获取表单参数
Try
data1 = c[' mem '].value# gets the value of the mem in the form
data2 = c[' CPU '].value# get the value of the CPU in the form
Except Keyerror: #如果没获取到数据, set the data to null
Data1 = ' '
data2 = ' '
If Data1 or data2: #判断是否获取到数据
f = open (' Cgi-bin/1.txt ', ' W ', encoding= ' UTF8 ') #创建文件
F.write (data1 + '% ' + ' \ n ') #写入mem的值
F.write (data2 + '% ' + ' \ n ') #写入cpu的值
F.close () #关闭文件
Client code:
#coding: UTF8
Import Psutil
Import Urllib.parse
Import Urllib.request
Test_data = {' Mem ':p sutil.virtual_memory (). Percent, ' CPU ':p sutil.cpu_percent ()}
Test_data_urlencode = Urllib.parse.urlencode (test_data). Encode (' UTF8 ') #把字典转为urlencode格式并解码为字节流
Requrl = "http://127.0.0.1:8000/cgi-bin/updata.py"
req = Urllib.request.Request (url=requrl,data=test_data_urlencode) #url带参数去请求服务器
Res_data = Urllib.request.urlopen (req) #提交请求
The client invokes the CGI update.py script to transfer the data to a text file in a fixed format
Python3 CGI data transfer