su-kaiyao translated

This commit is contained in:
su-kaiyao 2014-10-25 13:13:43 +08:00
parent 29258d0c85
commit c32f9205a1
2 changed files with 158 additions and 159 deletions

View File

@ -1,159 +0,0 @@
su-kaiyao translating
How to create and use Python CGI scripts
================================================================================
Have you ever wanted to create a webpage or process user input from a web-based form using Python? These tasks can be accomplished through the use of Python CGI (Common Gateway Interface) scripts with an Apache web server. CGI scripts are called by a web server when a user requests a particular URL or interacts with the webpage (such as clicking a "Submit" button). After the CGI script is called and finishes executing, the output is used by the web server to create a webpage displayed to the user.
### Configuring the Apache web server to run CGI scripts ###
In this tutorial we assume that an Apache web server is already set up and running. This tutorial uses an Apache web server (version 2.2.15 on CentOS release 6.5) that is hosted at the localhost (127.0.0.1) and is listening on port 80, as specified by the following Apache directives:
ServerName 127.0.0.1:80
Listen 80
HTML files used in the upcoming examples are located in /var/www/html on the web server. This is specified via the DocumentRoot directive (specifies the directory that webpages are located in):
DocumentRoot "/var/www/html"
Consider a request for the URL: http://localhost/page1.html
This will return the contents of the following file on the web server:
/var/www/html/page1.html
To enable use of CGI scripts, we must specify where CGI scripts are located on the web server. To do this, we use the ScriptAlias directive:
ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"
The above directive indicates that CGI scripts are contained in the /var/www/cgi-bin directory on the web server and that inclusion of /cgi-bin/ in the requested URL will search this directory for the CGI script of interest.
We must also explicitly permit the execution of CGI scripts in the /var/www/cgi-bin directory and specify the file extensions of CGI scripts. To do this, we use the following directives:
<Directory "/var/www/cgi-bin">
Options +ExecCGI
AddHandler cgi-script .py
</Directory>
Consider a request for the URL: http://localhost/cgi-bin/myscript-1.py
This will call the following script on the web server:
/var/www/cgi-bin/myscript-1.py
### Creating a CGI script ###
Before creating a Python CGI script, you will need to confirm that you have Python installed (this is generally installed by default, however the installed version may vary). Scripts in this tutorial are created using Python version 2.6.6. You can check your version of Python from the command line by entering either of the following commands (the -V and --version options display the version of Python that is installed):
$ python -V
$ python --version
If your Python CGI script will be used to process user-entered data (from a web-based input form), then you will need to import the Python cgi module. This module provides functionality for accessing data that users have entered into web-based input forms. You can import this module via the following statement in your script:
import cgi
You must also change the execute permissions for the Python CGI script so that it can be called by the web server. Add execute permissions for others via the following command:
# chmod o+x myscript-1.py
### Python CGI Examples ###
Two scenarios involving Python CGI scripts will be considered in this tutorial:
- Create a webpage using a Python script
- Read and display user-entered data and display results in a webpage
Note that the Python cgi module is required for Scenario 2 because this involves accessing user-entered data from web-based input forms.
### Example 1: Create a webpage using a Python script ###
For this scenario, we will start by creating a webpage /var/www/html/page1.html with a single submit button:
<html>
<h1>Test Page 1</h1>
<form name="input" action="/cgi-bin/myscript-1.py" method="get">
<input type="submit" value="Submit">
</form>
</html>
When the "Submit" button is clicked, the /var/www/cgi-bin/myscript-1.py script is called (specified by the action parameter). A "GET" request is specified by setting the method parameter equal to "get". This requests that the web server return the specified webpage. An image of /var/www/html/page1.html as viewed from within a web browser is shown below:
![](https://farm4.staticflickr.com/3933/14932853623_eff2df3260_z.jpg)
The contents of /var/www/cgi-bin/myscript-1.py are:
#!/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>"
The first statement indicates that this is a Python script to be run with the /usr/bin/python command. The print "Content-Type: text/html" statement is required so that the web server knows what type of output it is receiving from the CGI script. The remaining statements are used to print the text of the webpage in HTML format.
When the "Submit" button is clicked in the above webpage, the following webpage is returned:
![](https://farm4.staticflickr.com/3933/15553035025_d70be04470_z.jpg)
The take-home point with this example is that you have the freedom to decide what information is returned by the CGI script. This could include the contents of log files, a list of users currently logged on, or today's date. The possibilities are endless given that you have the entire Python library at your disposal.
### Example 2: Read and display user-entered data and display results in a webpage ###
For this scenario, we will start by creating a webpage /var/www/html/page2.html with three input fields and a submit button:
<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>
When the "Submit" button is clicked, the /var/www/cgi-bin/myscript-2.py script is called (specified by the action parameter). An image of /var/www/html/page2.html as viewed from within a web browser is shown below (note that the three input fields have already been filled in):
![](https://farm4.staticflickr.com/3935/14932853603_ffc3bd330e_z.jpg)
The contents of /var/www/cgi-bin/myscript-2.py are:
#!/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>"
As mentioned previously, the import cgi statement is needed to enable functionality for accessing user-entered data from web-based input forms. The web-based input form is encapsulated in the form object, which is a cgi.FieldStorage object. Once again, the "Content-Type: text/html" line is required so that the web server knows what type of output it is receiving from the CGI script. The data entered by the user are accessed in the statements that contain form["firstName"].value, form["lastName"].value, and form["position"].value. The names in the square brackets correspond to the values of the name parameters defined in the text input fields in **/var/www/html/page2.html**.
When the "Submit" button is clicked in the above webpage, the following webpage is returned:
![](https://farm4.staticflickr.com/3949/15367402150_946474dbb0_z.jpg)
The take-home point with this example is that you can easily read and display user-entered data from web-based input forms. In addition to processing data as strings, you can also use Python to convert user-entered data to numbers that can be used in numerical calculations.
### Summary ###
This tutorial demonstrates how Python CGI scripts are useful for creating webpages and for processing user-entered data from web-based input forms. More information about Apache CGI scripts can be found [here][1] and more information about the Python cgi module can be found [here][2].
--------------------------------------------------------------------------------
via: http://xmodulo.com/create-use-python-cgi-scripts.html
作者:[Joshua Reed][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](http://linux.cn/) 荣誉推出
[a]:http://xmodulo.com/author/joshua
[1]:http://httpd.apache.org/docs/2.2/howto/cgi.html
[2]:https://docs.python.org/2/library/cgi.html#module-cgi

View File

@ -0,0 +1,158 @@
如何创建和使用Python CGI脚本
===
你是否想使用Python语言创建一个网页或者处理用户从web表单输入的数据这些任务可以通过Python CGI(公用网关接口)脚本以及一个Apache web服务器实现。当用户请求一个指定URL或者和网页交互(比如点击""提交"按钮)的时候CGI脚本就会被web服务器启用。CGI脚本调用执行完毕后它的输出结果就会被web服务器用来创建显示给用户的网页。
### 配置Apache web服务器让其能运行CGI脚本 ###
在这个教程里我们假设Apache web服务器已经安装好并已运行。这篇教程使用的Apache web服务器(版本2.2.15用于CentOS发行版6.5)运行在本地主机(127.0.0.1)并且监听80端口如下面的Apache指令指定一样
ServerName 127.0.0.1:80
Listen 80
下面举例中的HTML文件存放在web服务器上的/var/www/html目录下并通过DocumentRoot指令指定(指定网页文件所在目录)
DocumentRoot "/var/www/html"
现在尝试请求URLhttp://localhost/page1.html
这将返回web服务器中下面文件的内容
/var/www/html/page1.html
为了启用CGI脚本我们必须指定CGI脚本在web服务器上的位置需要用到ScriptAlias指令
ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"
以上指令表明CGI脚本保存在web服务器的/var/www/cgi-bin目录请求URL里包含/cgi-bin/的将会搜索这个目录下的CGI脚本。
我们必须还要明确CGI脚本在/var/www/cgi-bin目录下有执行权限还要指定CGI脚本的文件扩展名。使用下面的指令
<Directory "/var/www/cgi-bin">
Options +ExecCGI
AddHandler cgi-script .py
</Directory>
下面访问URLhttp://localhost/cgi-bin/myscript-1.py
这将会调用web服务器中下面所示脚本
/var/www/cgi-bin/myscript-1.py
### 创建一个CGI脚本 ###
在创建一个Python CGI脚本之前你需要确认你已经安装了Python(这通常是默认安装的,但是安装版本可能会有所不同)。本篇教程使用的脚本是使用Python版本2.6.6编写的。你可以通过下面任意一命令(-V和--version参数将显示所安装Python的版本号)检查Python的版本。
$ python -V
$ python --version
如果你的Python CGI脚本要用来处理用户输入的数据(从一个web输入表单)然后你将需要导入Python cgi模块。这个模块可以处理用户通过web输入表单输入的数据。你可以在你的脚本中通过下面的语句导入该脚本
import cgi
你也必须修改Python CGI脚本的执行权限以防止web服务器不能调用。可以通过下面的命令增加执行权限
# chmod o+x myscript-1.py
### Python CGI例子 ###
涉及到Python CGI脚本的两个方案将会在下面讲述
- 使用Python脚本创建一个网页
- 读取并显示用户输入的数据,并且在网页上显示结果
注意Python cgi模块在方案2中是必需的因为这涉及到用户从web表单输入数据。
### 例子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脚本将被调用(通过action参数指定)。通过设置方法参数为"get"来指定一个"GET"请求,服务器将会返回指定的网页。/var/www/html/page1.html在浏览器中的显示情况如下
![](https://farm4.staticflickr.com/3933/14932853623_eff2df3260_z.jpg)
/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>"
第一行声明表示这是使用 /usr/bin/python命令运行的Python脚本。"Content-Type: text/html"打印语句是必需的这是为了让web服务器知道接受自CGI脚本的输出类型。其余的语句用来输出HTML格式的其余网页内容。
当"Submit"按钮点击,下面的网页将返回:
![](https://farm4.staticflickr.com/3933/15553035025_d70be04470_z.jpg)
这个例子的要点是你可以决定哪些信息可以被CGI脚本返回。这可能包括日志文件的内容当前登陆用户的列表或者今天的日期。在你处理时拥有所有python库的可能性是无穷无尽的。
### 例子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浏览器中的图片如下所示(注意,三个输入域已经被填写了)
![](https://farm4.staticflickr.com/3935/14932853603_ffc3bd330e_z.jpg)
/var/www/cgi-bin/myscript-2.py的内容如下
#!/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"].valueform["lastName"].value, and form["position"].value的语句中被接受。那些中括号中的名称和**/var/www/html/page2.html**文本输入域中定义的名称参数一致。
当网页上的"Submit"按钮被点击,下面的网页将被返回。
![](https://farm4.staticflickr.com/3949/15367402150_946474dbb0_z.jpg)
这个例子的要点就是你可以很容易地读取并显示用户在web表单上输入的数据。除了以字符串的方式处理数据你也可以用Python将用户输入的数据转化为可用于数值计算的数字。
### 结论 ###
本教程演示了如何使用Python CGI脚本创建网页并处理用户在网页表单输入的数据。查阅更多关于Apache CGI脚本的信息点击[这里][1]。查阅更多关于Python cgi模块的信息点击[这里][2]。
---
via: http://xmodulo.com/create-use-python-cgi-scripts.html
作者:[Joshua Reed][a]
译者:[su-kaiyao](https://github.com/su-kaiyao)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](http://linux.cn/) 荣誉推出
[a]:http://xmodulo.com/author/joshua
[1]:http://httpd.apache.org/docs/2.2/howto/cgi.html
[2]:https://docs.python.org/2/library/cgi.html#module-cgi