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

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

零下一度
Release: 2017-05-19 13:04:02
Original
2596 people have browsed it

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()#关闭文件
Copy after login
#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)#提交请求
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template