Python3 CGI programming tutorial

First, background note

Although long ago I heard an "early site realized by many cgi form", " C ++ can be written in the form of web pages by CGI " CGI also over time to have some concept , but have not really seen a CGI website is actually running, always or some lack of confidence.

Last week saw a tutorial on the rookie of CGI programming so they imitate realize it, but can not be found during a successful run (in fact, his back problem to say), then Baidu additional information see the implementation of a wide variety of ways to achieve that is not just parroting very irregular, so we recorded it.

This article achieve environmental: Ubuntu 16.04 + Python 3.7 + apache2

 

Two, apache2 configuration on Ubuntu

2.1 apache2 profile form

Ubuntu (precise point it should be said Dibian) on apache configuration files in / etc / apache2 directory, we first look at their directory structure, as follows:

xxx-available support for apache2 folder indicates the current function of the corresponding xxx-enabled represent the features enabled; xxx-enabled files in general is a soft link to a file in xxx-available.

Where the magic number is defined MIME things, envvars define some variables for use in other profiles, both generally do not modify our point of view we need to modify the (?):

/ etc / apache2 / 
| - apache2.conf # This file contains the configuration file by IncludeOptional the following (each directory) 
| `- ports.conf # This file is mainly configured listening port 
| - under the directory mods-enabled # the configuration file is for a module of 
| | - * .load # .load file is usually loaded modules corresponding .so file LoadModule command 
| `- * .conf # .conf file is usually the same name as the file is loaded .load themselves need to configure the module, we generally do not pipe 
| - conf-enabled # files in this directory are generally configured for a particular function 
| `- * .conf 
` - # sites-Enabled this directory file is used to configure VirtualHost 
        `- * .conf

apache configuration file is divided into so many, it is to allow us to easily know what a function corresponding configuration work is; of course, for people who are not familiar with it may not feel easy but complex, then we must know that this is just a kind of organization is not mandatory but agreed on the syntax, so all you have to configure all written in a apache2.conf this file is also possible (but note that for the first apache2 configuration does not take effect after the entry into force of the first principle, if the IncludeOptional configuration values ​​before and have an item that you added in apache2.conf the value does not take effect).

 

2.2 apache2 start and stop operation of a functional configuration

From the introduction section above, we can conclude that you want to enable a feature at xxx-enabled directory, create a soft link pointing to the function at xxx-available directory corresponding file; you want to disable a feature to remove the feature the appropriate soft link at xxx-enable directory.

This operation is feasible, but Ubuntu also provides a direct order to achieve this, we can remove this switch directories, soft links command forget writing format, such as missing links plague.

mod is the corresponding start and stop with Imperative a2enmod / a2dismod, conf corresponding start and stop command is a2enconf / a2disconf, site corresponding to the start and stop command is a2ensite / a2dissite.

For example, here we want to enable disabled cgi support functions corresponding command is:

# The difference between these two modules cgid cgi and I still do not understand what is, in fact, seem only cgid on it (?) 
# Enabled, cgi, cgid two names is the name of the file in the mods-available directory 
sudo cgi cgid a2enmod 
# disabled, cgi, cgid two names is the name of the next mods-enabled directory you want to delete the soft link 
sudo a2dismod cgi cgid

There may be a small partner still does not feel very convenient ah, I still get to see the file name under the mods-available or mods-enabled; that in fact there is another wording, you can start without a name you want to enable the function / disabled, then the command will list the names of all currently available enable / disable the function, then re-enter the name you want to enable / disable the function can, as shown below:

 

Three, Python3 CGI programming

3.1 apache2 configuration support cgi

Summed up the second largest festival of knowledge, use the following command to enable:

# Enable module support. Then again I do not understand the difference cgi and cgid, so the two are simply enable
 sudo a2enmod cgi cgid 
# Enable the default configuration of cgi. 
sudo a2enconf serve-CGI- bin 
# set to take effect restart apache using 
sudo systemctl restart apache2

 

3.2 Targeted transformation

Targeted transformation here refers to two points, one ahead of us but we have not started to apache cgi cgi pointed out what language to deal with, and second, we want to specify the directory cgi file is / var / www / cgi-bin.

We first / etc / apache2 / view the serve-cgi-bin.conf the configuration conf-enabled directory, the default is as follows:

<IfModule mod_alias.c>
        <IfModule mod_cgi.c>
                Define ENABLE_USR_LIB_CGI_BIN
        </IfModule>

        <IfModule mod_cgid.c>
                Define ENABLE_USR_LIB_CGI_BIN
        </IfModule>

        <IfDefine ENABLE_USR_LIB_CGI_BIN>
                ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
                <Directory "/usr/lib/cgi-bin">
                        AllowOverride None
                        Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
                        Require all granted
                </Directory>
        </IfDefine>
</IfModule>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
View Code

One can see that no configuration file handling, and second, setting the file folder is / usr / lib / cgi-bin /. We use the "AddHandler cgi-script .cgi .py" specified cgi .cgi and specify the file name extension .py (usually written no matter what language should be saved as .cgi but also allows for pytho into the habit of saving .py) under the other using "ScriptAlias ​​/ cgi-bin / / var / www / cgi-bin /" specifies what happens path "/ cgi-bin /" in the url turned to "/ var / www / cgi-bin /" directory to find file, the final amended as follows:

<IfModule mod_alias.c>
        <IfModule mod_cgi.c>
                Define ENABLE_USR_LIB_CGI_BIN
        </IfModule>

        <IfModule mod_cgid.c>
                Define ENABLE_USR_LIB_CGI_BIN
        </IfModule>

        <IfDefine ENABLE_USR_LIB_CGI_BIN>
                ScriptAlias /cgi-bin/ /var/www/cgi-bin/
                <Directory "/var/www/cgi-bin/">
                        AllowOverride None
                        Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
                        Require all granted
                        AddHandler cgi-script .cgi .py
                </Directory>
        </IfDefine>
</IfModule>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

 

Write 3.3 python file

Note two things:

First, the #! Shell parses the specified file at the beginning of the essential (and shell have to change their own python path where), because although we have a cgi process .py file is specified, but in essence apache still do not know which shell .py should be used to deal with .py file.

Second, most of the tutorials are written directly onto print (), I am here specifically written in the form of a method, mainly in order to emphasize that the final cgi python helloworld.py so run, you end up html output a response on the line, do not need you up on the print ().

# Create / var / www / cgi-bin / directory 
sudo mkdir / var / www / cgi-bin / 
# Create helloworld.py file and write the contents 
# I do not know why the cat sudo direct write will be prompted to do so Permission denied it trouble 
sudo Touch /var/www/cgi-bin/helloworld.py 
sudo chmod 777 /var/www/cgi-bin/helloworld.py 
sudo CAT> /var/www/cgi-bin/helloworld.py < <EOF
 #! / opt / miniconda3 / bin / Python 

DEF main (): 
        Print ( "Content-of the type: text / HTML") 
        Print () # blank line tells the server end head 
        Print ( '<HTML > ') 
        Print ( ' < head > ') 
        Print (' < Meta charset = "UTF-. 8">')
        print ('<title>Hello Word - My First CGI Programe !</title>')
        print ('</head>')
        print ('<body>')
        print ('<h2>Hello Word! This is my first CGI programe !</h2>')
        print ('</body>')
        print ('</html>') 
# If you write from the file using vi After writing so remember to add a file executable permissions
EOF

Main ()

 

3.4 operating results presentation

Since the front do a lot of configuration, just in case a reboot is recommended before accessing an apache:

sudo systemctl restart apache2

Operating results are as follows:

 

3.5 running process analysis [optional]

Request - response packets as follows:

We create in / var / www under / cgi-bin directory error.py file, write the following contents and save it (mostly no shell will run the line error):

def main():
        print("Content-type:text/html")
        print()                             # 空行,告诉服务器结束头部
        print('<html>')
        print('<head>')
        print('<meta charset="utf-8">')
        print('<title>Hello Word - My First CGI Programe !</title>')
        print('</head>')
        print('<body>')
        print('<h2>Hello Word! This is my first CGI programe !</h2>')
        print('</body>')
        print('</html>')

main()
View Code

重启apache后访问两次error.py页面两次,然后查看错误日志(默认是/var/log/apache2/error.log)末尾的内容,如果没有意外应该是如下的两个报错;报错没有什么问题,问题是我们可以看到两次访问报错的进程id是不一样的,这就认证了cgi每次都重新启动一个进程的说法(本质差不多和自己手动运行python文件差不多)。

 

参考:

https://www.runoob.com/python3/python3-cgi-programming.html

Guess you like

Origin www.cnblogs.com/lsdb/p/11287448.html