Python3 CGI data transfer

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.