python的CGi编程学习

python的CGI编程的学习记录

在遇到了各种问题的情况下,跌跌撞撞的完成了第一个CGI程序,成功显示,接下来便是对CGI编程的进一步学习:

  • 获取CGI环境变量

    win环境python3.6的代码如下

#!D:\software\Microsoft Visual Studio\Shared\Python36_64\python.exe
# -*- coding: utf-8 -*-

import os
import codecs, sys 
import cgi
sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer)

print ("Content-type: text/html")
print ()
print ("<meta charset=\"utf-8\">")
print ("<b>环境变量</b><br>")
print ("<ul>")
for key in os.environ.keys():
    print ("<li><span style='color:green'>%30s </span> : %s </li>" % (key,os.environ[key]))
print ("</ul>")

将代码保存为test.py之后放在cgi-bin文件夹下,在浏览器中输入localhost/cgi-bin/test.py,即可以看到环境变量信息。

  • 使用get和post方法向服务器传递信息

    首先是get方法。这种方法可以在URL中包含关键词,直接向python模块传递信息,其python代码如下:

#!D:\software\Microsoft Visual Studio\Shared\Python36_64\python.exe
# -*- coding: utf-8 -*-
# filename:test.py

import os
import codecs, sys 
sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer)

# CGI处理模块
import cgi, cgitb 

# 创建 FieldStorage 的实例化
form = cgi.FieldStorage() 

# 获取数据
site_name = form.getvalue('name')
site_url  = form.getvalue('url')

print ("Content-type:text/html\n\n")
print ("<html>")
print ("<head>")
print ("<meta charset=\"utf-8\">")
print ("<title>菜鸟教程 CGI 测试实例</title>")
print ("</head>")
print ("<body>")
print ("<h2>%s官网:%s</h2>" % (site_name, site_url))
print ("</body>")
print ("</html>")

将以上代码保存为hello_get.py,有两种方法可以在网页上显示想要的内容。
第一种是直接在URL中输入以下内容:

localhost/cgi-bin/test.py?name=菜鸟教程&url=http://www.runoob.com

这个时候就可以在网页上显示如下内容
这里写图片描述

另一种方法是使用表单上传:其html代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<form action="/cgi-bin/hello_get.py" method="get">
站点名称: <input type="text" name="name">  <br />

站点 URL: <input type="text" name="url" />
<input type="submit" value="提交" />
</form>
</body>
</html>

保存为html文件,hello_get.html。可以在cgi-bin文件夹下新建一个test文件夹,将此html文件存放进去,访问可以使用以下地址:

localhost/cgi-bin/test/hello_get.html

访问该地址后将会得到一个提交站点名称,以及站点URL的界面,此时点提交,将会在网页上显示自己提交的内容。

接下来是post方法,post方法和get方法大同小异,需要将html代码中的method由get改成post。

  • 使用CGI传递(CheckBox)选项数据

其html代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<form action="/cgi-bin/checkbox.py" method="POST" target="_blank">
<input type="checkbox" name="runoob" value="on" /> 菜鸟教程
<input type="checkbox" name="google" value="on" /> Google
<input type="submit" value="选择站点" />
</form>
</body>
</html>

其python代码如下:

#!D:\software\Microsoft Visual Studio\Shared\Python36_64\python.exe
# -*- coding: utf-8 -*-
# filename:test.py

import os
import codecs, sys 
sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer)

# 引入 CGI 处理模块 
import cgi, cgitb 

# 创建 FieldStorage的实例 
form = cgi.FieldStorage() 

# 接收字段数据
if form.getvalue('google'):
   google_flag = "是"
else:
   google_flag = "否"

if form.getvalue('runoob'):
   runoob_flag = "是"
else:
   runoob_flag = "否"

print ("Content-type:text/html")
print ()
print ("<html>")
print ("<head>")
print ("<meta charset=\"utf-8\">")
print ("<title>菜鸟教程 CGI 测试实例</title>")
print ("</head>")
print ("<body>")
print ("<h2> 菜鸟教程是否选择了 : %s</h2>" % runoob_flag)
print ("<h2> Google 是否选择了 : %s</h2>" % google_flag)
print ("</body>")
print ("</html>")
  • 使用CGI传递Radio数据

其html代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<form action="/cgi-bin/radiobutton.py" method="post" target="_blank">
<input type="radio" name="site" value="runoob" /> 菜鸟教程
<input type="radio" name="site" value="google" /> Google
<input type="submit" value="提交" />
</form>
</body>
</html>

其python代码如下:

#!D:\software\Microsoft Visual Studio\Shared\Python36_64\python.exe
# -*- coding: utf-8 -*-
# filename:test.py

import os
import codecs, sys 
sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer)

# 引入 CGI 处理模块 
import cgi, cgitb 

# 创建 FieldStorage的实例 
form = cgi.FieldStorage() 

# 接收字段数据
if form.getvalue('site'):
   site = form.getvalue('site')
else:
   site = "提交数据为空"

print ("Content-type:text/html")
print ()
print ("<html>")
print ("<head>")
print ("<meta charset=\"utf-8\">")
print ("<title>菜鸟教程 CGI 测试实例</title>")
print ("</head>")
print ("<body>")
print ("<h2> 选中的网站是 %s</h2>" % site)
print ("</body>")
print ("</html>")
  • 使用CGI传递Textarea数据

其html代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<form action="/cgi-bin/textarea.py" method="post" target="_blank">
<textarea name="textcontent" cols="40" rows="4">
在这里输入内容...
</textarea>
<input type="submit" value="提交" />
</form>
</body>
</html>

其python代码如下:

#!D:\software\Microsoft Visual Studio\Shared\Python36_64\python.exe
# -*- coding: utf-8 -*-
# filename:test.py

import os
import codecs, sys 
sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer)

# 引入 CGI 处理模块 
import cgi, cgitb 

# 创建 FieldStorage的实例 
form = cgi.FieldStorage() 

# 接收字段数据
if form.getvalue('textcontent'):
   text_content = form.getvalue('textcontent')
else:
   text_content = "没有内容"

print ("Content-type:text/html")
print ()
print ("<html>")
print ("<head>")
print ("<meta charset=\"utf-8\">")
print ("<title>菜鸟教程 CGI 测试实例</title>")
print ("</head>")
print ("<body>")
print ("<h2> 输入的内容是:%s</h2>" % text_content)
print ("</body>")
print ("</html>")
  • 使用CGI传递下拉数据

其html代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<form action="/cgi-bin/dropdown.py" method="post" target="_blank">
<select name="dropdown">
<option value="runoob" selected>菜鸟教程</option>
<option value="google">Google</option>
</select>
<input type="submit" value="提交"/>
</form>
</body>
</html>

其python代码如下:

#!D:\software\Microsoft Visual Studio\Shared\Python36_64\python.exe
# -*- coding: utf-8 -*-
# filename:test.py

import os
import codecs, sys 
sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer)

# 引入 CGI 处理模块 
import cgi, cgitb 

# 创建 FieldStorage的实例 
form = cgi.FieldStorage() 

# 接收字段数据
if form.getvalue('dropdown'):
   dropdown_value = form.getvalue('dropdown')
else:
   dropdown_value = "没有内容"

print ("Content-type:text/html")
print ()
print ("<html>")
print ("<head>")
print ("<meta charset=\"utf-8\">")
print ("<title>菜鸟教程 CGI 测试实例</title>")
print ("</head>")
print ("<body>")
print ("<h2> 选中的选项是:%s</h2>" % dropdown_value)
print ("</body>")
print ("</html>")
  • 在CGI中使用cookie

首先是设置一个cookie。可以使用如下python代码:

#!D:\software\Microsoft Visual Studio\Shared\Python36_64\python.exe
# -*- coding: utf-8 -*-

print('Content-type:text/html')
print("Set-Cookie:name='yan';expires=Wed,8 Aug 2018 18:30:00 GMT")
print()
print("""
<html>
    <head>
        <meta charset="utf-8">
        <title> The site of yan </title>
    <head>
        <body>
            <h1> Cookie set OK! </h1>
        </body>
</html>
""")

接下来可以访问该地址,得到cookie设置成功的提示。然后可以获取cookie信息,可以使用如下python代码:

#!D:\software\Microsoft Visual Studio\Shared\Python36_64\python.exe
# -*- coding: utf-8 -*-

import codecs ,sys
sys.stdout = codecs.getwriter('utf8')(sys.stdout.buffer)

# 导入模块
import os
from http import cookies

print ("Content-type: text/html")
print ()

print ("""
<html>
    <head>
        <meta charset = "utf-8">
        <title> The sie of chen </title>
    </head>
    <body>
        <h1> reading cookie 信息 </h1>
""")
if 'HTTP_COOKIE' in os.environ:
    cookie_string = os.environ.get('HTTP_COOKIE')
    c = cookies.SimpleCookie()
    c.load(cookie_string)

    try:        # 捕捉异常
        data = c['name'].value
        print ("<h2> cookie data: "+ data + "</h2> <br>")
    except KeyError:
        print ("cookie 没有设置或者已经过时 <br>")


print ("""
    </body>
    </html>
    """)

访问该地址,可以得到获取的cookie信息。

  • 上传文件

其html代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
 <form enctype="multipart/form-data" 
                     action="/cgi-bin/save_file.py" method="post">
   <p>选中文件: <input type="file" name="filename" /></p>
   <p><input type="submit" value="上传" /></p>
   </form>
</body>
</html>

其python代码如下:

#!D:\software\Microsoft Visual Studio\Shared\Python36_64\python.exe
# -*- coding: utf-8 -*-

import cgi, os
import cgitb; cgitb.enable()

form = cgi.FieldStorage()

# 获取文件名
fileitem = form['filename']

# 检测文件是否上传
if fileitem.filename:
   # 设置文件路径 
   fn = os.path.basename(fileitem.filename)
   open('/tmp/' + fn, 'wb').write(fileitem.file.read())

   message = '文件 "' + fn + '" 上传成功'

else:
   message = '文件没有上传'

print ("""\
Content-Type: text/html\n
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
   <p>%s</p>
</body>
</html>
""" % (message,))

访问html文件,选择文件会提示文件上传成功。
以上均整理自菜鸟教程
同时也遇到了一个没有解决的大问题,就是我将html文件保存后,在地址栏输入地址访问它,会得到500错误,查看error log信息如下

[Mon Aug 06 18:30:45.542820 2018] [win32:error] [pid 9316:tid 1208] [client ::1:59484] AH02102: D:/software/wamp64/bin/apache/apache2.4.33/cgi-bin/tester/hello_post.html is not executable; ensure interpreted scripts have "#!" or "'!" first line

很纠结,需要进一步的学习来解决。[这里写链接内容]

猜你喜欢

转载自blog.csdn.net/qq_42856481/article/details/81479360