您的位置:首页 > 运维架构 > Apache

ubuntu14.04 apache2 CGI 入门实战

2016-02-27 18:41 615 查看
apache2服务器配置:

修改/etc/apache2下的apache2.conf文件:

<Directory /var/www/cgi-bin>
Options  +ExecCGI
AllowOverride None
Require all granted
AddHandler cgi-script .py
</Directory>
另外在文件最后添加 ServerName 127.0.0.1:80

修改/etc/apache2/sites-enabled下的ooo-default文件:



在/etc/apache2/mods-enabled目录下的mime.load文件下添加:

LoadModule cgi_module modules/mod_cgi.so

以上是配置过程,接下来是写html和cgi脚本:

(1)使用python脚本展示一个网页

/var/www/html/page1.html

<html>
<h1>Test Page 1</h1>
<form name="input" action="/cgi-bin/myscript-1.py" method="get">
<input type="submit" value="Submit">
</form>
</html>
/var/www/cgi-bin/myscript-1.py

#!/usr/bin/python
print"Content-Type: text/html"
print""
print"<html>"
print"<h2>CGI Script Output</h2>"
print"<p>This page was generated by a Python CGI script.</p>"
print"</html>"
对此文件赋予可执行的权限
sudo chmod o+x myscript-1.py
操作过程:





(2)读取并显示用户输入的数据,并将结果显示在网页上

通过创建一个含有三个输入域和一个提交按钮的网页/var/www/html/page2.html开始

<html>
<h1>Test Page 2</h1>
<form name="input" action="/cgi-bin/myscript-2.py" method="get">
First Name: <input type="text" name="firstName"><br>
Last Name: <input type="text" name="lastName"><br>
Position: <input type="text" name="position"><br>
<input type="submit" value="Submit">
</form>
</html>当"Submit"按钮点击,/var/www/cgi-bin/myscript-2.py脚本被执行(通过action参数指定)。/var/www//html/page2.html显示在web浏览器中的图片如下所示(注意,三个输入域已经被填写好了):
#!/usr/bin/python
import cgi
form = cgi.FieldStorage()
print "Content-Type: text/html"
print ""
print "<html>"
print "<h2>CGI Script Output</h2>"
print "<p>"
print "The user entered data are:<br>"
print "<b>First Name:</b> " + form["firstName"].value + "<br>"
print "<b>Last Name:</b> " + form["lastName"].value + "<br>"
print "<b>Position:</b> " + form["position"].value + "<br>"
print "</p>"
print "</html>"import cgi语句用来确保能够处理用户通过web输入表单输入的数据。web输入表单被封装在一个表单对象中,叫做cgi.FieldStorage对象。一旦开始输出,"Content-Type: text/html"是必需的,因为web服务器需要知道接受自CGI脚本的输出格式。用户输入的数据在包含form["firstName"].value,form["lastName"].value,和 form["position"].value的语句中可以得到。那些中括号中的名称和/var/www/html/page2.html文本输入域中定义的名称参数一致。
操作过程:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Ubuntu apache2 cgi