Home  >  Article  >  Backend Development  >  Detailed explanation of cgi writing data example code to text or database

Detailed explanation of cgi writing data example code to text or database

零下一度
零下一度Original
2017-05-19 13:04:022531browse

Use cgi to write data to text or database

1. Start the cgi service

python -m http.server --cgi port[Port is optional and defaults to 8000]

update.py code

#coding:utf8
import cgi
c = cgi.FieldStorage()#获取表单参数
try:
   data1 =  c['mem'].value#获取表单中mem的值
   data2 =  c['cpu'].value#获取表单中cpu的值
except KeyError:#如果没获取到数据,就把数据设置为空
    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()#关闭文件
#coding:utf8
import psutil
import urllib.parse
import urllib.request
test_data = {'mem':psutil.virtual_memory().percent,'cpu':psutil.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 calls cgi’s update.py script to transfer the data to be transmitted to a text file in a fixed format

【Related Recommendations】

1. What is CGI? Detailed introduction to Python CGI programming

2. Share an example tutorial on running Python scripts in CGI mode on IIS

3. Use CGI module to create Simple web page tutorial example

4. Share an example tutorial of Python CGI programming

5. Detailed explanation of XML and sample code of modern CGI applications

6. FastCGI process unexpectedly exited causing 500 error

The above is the detailed content of Detailed explanation of cgi writing data example code to text or database. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn