CGI(Common Gateway Interface) programming in python


  • CGI is the most used method, as it is the easiest to configure and is available on almost all Web servers without having to install additional software.
  • It is essentially a protocol to connect an application, written in any language with a Web server.

Configuring a Web Server for CGI

  • Although I have said that the web server configuration is beyond the scope.
  • I think that it is reasonable to offer a few recommendations to help you configure a server for CGI
  • In the server configuration file there should be specifications that scripts can be executed via CGI, in which directories and how they will be named.
  • If we want our scripts to be located at /var/www/apache2-default/cgi-bin, we have to include the following lines in the server’s configuration file.
  • <Directory /var/www/apache2-default/cgi-bin>
          Options +ExecCGI
    </Directory>

    To specify that the executable scripts are those that have the file extension .py, the following line is added

    AddHandler cgi-script .py

    If the configuration file already has a line with the file extensions registered, you only need to add .py to it.

    AddHandler cgi-script .cgi .pl .py

    Finally we have to configure the ScriptAlias variable to where scripts are stored.

    ScriptAlias /cgi-bin/ /var/www/apache2-default/cgi-bin/

    This is all there is to the server configuration file. The only thing that is left to do is make sure that the script has the Apache user permissions. If you have access to the server’s terminal you can enter

    chmod a+x MyScript.py

Testing the Server with Our Script

To confirm that our server is ready to execute CGI programs, we can do that with the following code:

    1 #!/usr/bin/env python
    2 print("Content-Type: text/html\n")
    3 print("<html><head><title>Test page</title></head><body>")
    4 print("<h1>HELLO WORLD!</h1>")
    5 print("</body></html>")

Explanation

  • The first line indicates the location of the Python interpreter. Usually, this line is optional and we add it only when we want to run the script directly without first having to start the Python interpreter but for CGI programs this line is mandatory.
  • The second line is important for the web server to know that it is going to be sent an HTML page.
  • Wehave to send the string Content-Type/html followed by two carriage returns.
  • Although on line two there is only one implicit carriage return (\n), the other one is added by the print command.
  • The rest of the program is similar to the others that we’ve done up to this point, the difference being that we print HTML code to be read by the browser.