python CGI programming practice

Article Updated: 2020-03-05

Note 1: Install the python See: installation of python and basic grammar
Note 2: Configure a web environment See also: Windows & Linux using an integrated environment to build web server
Note 3: linux configuration CGI See: Linux configuration python3 CGI
Note 4: Windows Configuration CGI See also: Windows CGI configured for use at ambient python

A, Web server support and configuration

Prior to CGI programming, make sure the Web server that supports CGI, which is configured to handle CGI program. All of the CGI program to be executed by the HTTP server stored in a directory preconfigured. This directory is a directory called CGI, and is named / var / www / cgi-bin directory conventionally. By convention, CGI has a file extension .cgi, but the file extension can be a Python language script .py.

// From the original tutorial] [EBEY, non-commercial please retain the original link: https: //www.yiibai.com/python/python_cgi_programming.html

By default, Linux server is configured to run only scripts in the / var / www / cgi-bin directory in. If you want to run CGI programs in other directories, you need to change the configuration file. There are two ways.

1, provided the ScriptAlias ​​(Method a)

In the /etc/httpd/conf/httpd.confmain configuration file, find the ScriptAliasline, it will add the directory you need, such as:

ScriptAlias  /test/  "/var/www/test/"

The above code / test / path is your web access, / var / www / test / your web access path corresponding to the actual local path.

After configuration is complete, save and exit and restart the httpd service can be.

Note 1: After the above path configuration, all files in this directory as CGI program processing, if the time you put into an HTML file, time of the visit to be wrong.
Note 2: The path to the final /no less, less error.

2, corresponding to the configuration directory (Method B)

Writes the following in the main configuration file:

# 下面的目录为你要设定的目录
<Directory "/var/www/test/">
    Options ExecCGI
</Directory>

# 找到 AddHandler 所在行,加入你要添加的后缀,这里添加 .py
AddHandler cgi-script .cgi .py

After this setting, in this directory to .pythe end of the file as a cgiprogram processing other files processed normally.

Second, the CGIprogram practice

1, a statement to explain the program and encoder

CGI program needs at the beginning of the program statement program interpreter, the interpreter program is what the program is executed.

With python example:

Windows Disclaimer: #! "D:\program|python37\python.exe", attention must be declared to .exethe file.
Linux Disclaimer: #! /usr/bin/env python3can also be used#!/usr/bin/python3

And then the second line declares the program code: # -*- coding:UTF-8 -*-Note, the program code only within the range of the front two rows declared valid.

2, the head output response (HTTP header) information

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

Some important HTTP header is as follows:

Header description
Content-type: Returns the MIME format string definition file. Such as Content-type: text / html
Expires:Date Date information becomes invalid. This should be the browser used to determine when a page needs to be refreshed. Effective date format string should be January 1, 1998 12:00:00 GMT.
Location: URL It should return the replacement request URL URL's. This field may be used to redirect the request to any file.
Last-modified: Date Date of last modification of the resource.
Content-length: N Length of the data, in bytes is returned. Browser uses this value to report the estimated download time of a file.
Set-Cookie:String By providing the cookie string passing

Output header later to finish 1-2 output blank lines print("\n")to tell the server header portion of the end, otherwise it will error.

3, CGI environment variables.

All the CGI programs can use the following environment variables:

Environment Variables description
CONTENT_TYPE Data type of content. When the client sends the content to the attached server. For example, the file uploads.
CONTENT_LENGTH Query length information. It applies only to the POST request.
HTTP_COOKIE Returns the key and value pairs of the form set Cookie.
HTTP_USER_AGENT User-Agent request header field contains information about the user agent initiates a request. Name your web browser.
PATH_INFOTCGI Path to the script.
QUERY_STRING The method of information transmission request is GET URL-encoded.
REMOTE_ADDR IP address of the remote host sends the request. This can be used to record or for the purpose of certification is to be useful.
REMOTE_HOST Fully qualified host name sent the request. If this information is not available, it can be used to obtain the IP address REMOTE_ADDR.
REQUEST_METHOD The method for manufacturing requirements. The most commonly used method is GET and POST.
SCRIPT_FILENAMECGI The full path to the script.
SCRIPT_NAMECGI Name of the script.
SERVER_NAME Host name or IP address of the server
SERVER_SOFTWARE Software name and version of the server is running.

We use these variables to import osa package, for example:

#! /usr/bin/env python
# -*- coding:UTF-8 -*-
print('Content-Type: text/html; charset=utf-8\n')

import os
print("你好")
print("<br>你的IP是:%s"%os.environ['REMOTE_ADDR'])

4, GET / POST method

GET method is applicable to explicitly convey information, content will appear in the URL, there is a length limit of 1024 characters.
POST method no size limitations implicit transmission, it is more secure.

For example:
GET: Access /cgi-bin/test.py?key=hello, will deliver the value helloof the keyto cgi-program.
POST: access /cgi-bin/test.pyand value passed to the cgiprogram.

Both may be received using the same script, cgithe program may be used to receive and process this value.

#! /usr/bin/env python3
# -*- utf-8 -*-
# 导入处理模块
import cgi, cgitb

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

# 进行赋值操作
getvalue = form.getvalue('key')

# 输出报文头并换行结束头部
print("Content-type:text/html\n")

# 输出HTML代码
print("<html>")
print("<head>")
print("<title>Get value program!</title>")
print("</head>")
print("<body>")
print("You have put the value: %s"%getvalue)
print("</body>")
print("</html>")

5, using the CGI program cookies

HTTP is a stateless protocol, but if you want visitors to your site from a page to jump to another page when stay logged in, you can use cookiesto achieve.

cookies is a server request a simple piece of text stored on a visitor's computer hard drive, this text identifies the visitor's identity.

When a visitor to jump from one page to another page, the browser will bring this text, this text server checks to determine the identity of the visitor.

cookies 5 is a variable-length plain text data.

value description
Expires cookie expiration time, if left blank it means to quit the browser that is expired
Domain cookie in which the domain name of your site can take effect
Path Which pages path can take effect on the effective domain name of your site, if left blank it means that all take effect
Secure Specifies whether connections to transfer over a secure HTTPS cookie
Name=Value cookies of key information, which is the name of the cookie and a value, you can set up multiple

for example:

print "Set-Cookie:UserID=mingzi;"
print "Set-Cookie:Password=mima123;"
print "Set-Cookie:Expires=Tuesday, 3-Dec-2020 08:30:00 GMT";"
print "Set-Cookie:Domain=www.xxxx.com;"
print "Set-Cookie:Path=/test;"
print "Content-type:text/html"

So how do you get CGI cookie do?

#!/usr/bin/python
# -*- utf-8 -*-
print("Content-type:text/html\n")

# Import modules for CGI handling 
from os import environ
import cgi, cgitb

if environ.has_key('HTTP_COOKIE'):
   for cookie in map(strip, split(environ['HTTP_COOKIE'], ';')):
      (key, value ) = split(cookie, '=');
      if key == "UserID":
         user_id = value

      if key == "Password":
         password = value

print "User ID  = %s" % user_id
print "Password = %s" % password

三、Enjoy!

Published 75 original articles · won praise 8 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_21516633/article/details/104680465