python15--CGI编程
2020-08-04 本文已影响0人
minisummer
哈喽,大家好!我是minisummer!首先感谢您的关注!
今天给大家分享的内容是python的CGI编程。
什么是CGI编程
CGI(Common Gateway Interface),通用网关接口,它是一段程序,运行在服务器上如:HTTP服务器,提供同客户端HTML页面的接口。
mac下xampp配置CGI编程
修改/Applications/XAMPP/xamppfiles/etc/httpd.conf配置文件
ScriptAlias /cgi-bin/ "/Applications/XAMPP/xamppfiles/cgi-bin/"
<Directory "/Applications/XAMPP/xamppfiles/cgi-bin">
AllowOverride All
Options All
Options ExecCGI
Order allow,deny
Allow from all
</Directory>
AddHandler cgi-script .cgi .py

python3编写第一个CGI程序
新建文件名为hello.py,并将文件放置/Applications/XAMPP/xamppfiles/cgi-bin路径下,并修改文件权限为755:chmode 755 hello.py
开头的/usr/bin/env python请自行替换成本地的python解释器。
#! /usr/bin/env python
# -*- coding: UTF-8 -*-
# HTTP头部的一部分,它会发送给浏览器告诉浏览器文件的内容类型。\r\n\r\n不能省略,否则报错
print("Content-type:text/html\r\n\r\n")
print('<html>')
print('<head>')
print('<meta charset="utf-8">')
print('<title>Hello Word - 我的第一个 CGI 程序!</title>')
print('</head>')
print('<body>')
print('<h2>Hello Word! 我是来自minisummer的第一CGI程序</h2>')
print('</body>')
print('</html>')
在浏览器输入网址:localhost:端口/cgi-bin/hello.py

CGI脚本输出CGI的环境变量
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "minisummer"
# date:2020/8/4 20:36
# TODO: CGI脚本输出CGI的环境变量
import os
print("Content-type: text/html\r\n\r\n")
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>")

请大家多多指教~
以上内容希望对你有帮助,有被帮助到的朋友欢迎点赞,评论。
注:转载请注明出处,商用请征得作者本人同意,谢谢!!!