Sample CGI Script

CGI (Common Gateway Interface) Scripts

The simplest CGI script that can be considered interesting involves printing out an HTTP header («Content-type: text/html») and a Web page. In addition, you might want to handle any incoming inputs from things like HTML forms or request parameters. In the earliest days of CGI, shell scripts were sometimes used to do things like this, so the principles are not particularly advanced.

Configuration

  1. Find out which user runs the Web server — it’s not often the same one as your own user, and it may be one with very limited permissions.
  2. Check the server configuration to see if it lets you run scripts in a particular directory. Make sure that if you’re using a configuration file for a particular directory, the global configuration permits you to define CGI script directories in that directory-local configuration file — some sites stop their users from altering such settings in such a way.
  3. Check the permissions from the top of the filesystem down to the directory where the script resides. The Web server user must be able to read and open/execute all the directories from the top right down to the script.
  4. Make sure your script is readable and executable by the Web server user.
  5. Make sure that the first line of the script refers to an interpreter that the Web server user can run. Things like /usr/bin/env python might not have any meaning to the Web server user because the python program may not be on the user’s PATH.

In addition you should make sure your script has the correct **line endings** for your server.

Sample Code

The following code attempts to combine simple output of a Web page with the processing of input from users viewing the page. You may wish to choose the actual first line of the script based on one of the first two lines provided below — the first one for Windows and dependent on the Python install path, whereas the second may only work on UNIX-like systems.

 1  #!C:\Python27\python.exe -u  2  #!/usr/bin/env python  3    4  import cgi  5  import cgitb; cgitb.enable() # for troubleshooting  6    7  print "Content-type: text/html"  8  print  9    10  print """   11   12    13     14    15   16    17   

Sample CGI Script

18 """ 19 20 form = cgi.FieldStorage() 21 message = form.getvalue("message", "(no message)") 22 23 print """ 24 25

Previous message: %s 26 27

form 28 29 "post" action="index.cgi"> 30

message: "text" name="message"/>

31
32 33
34 35 36 """ % cgi.escape(message)

See Also

  • WebProgramming — the natural next step beyond simple CGI scripts.
  • cgi module documentation
  • Cookie module documentation
  • Python CGI tutorial — setup in a shared host, forms, debug, shell commands, cookies, etc
  • python CGI tutorial — w/ hints about maintaining sessions either through forms or through cookies
  • python CGI tutorial — w/ hints about printing out tracebacks
  • other internet protocol module documentation
  • Writing CGI Scripts in Python
  • Voidspace Python CGI collection — Working Python CGI scripts to use and/or study

Discussion

  • We need a good python CGI framework — Sridhar R
    • Nevow and Wallaby Define «framework,» though. Do you mean something like a Django-type deal or something that just makes it easier to write CGI apps?

    There are many frameworks for Python Web Application TurboGears Django Zope ModPython Pso Aquarium Cheetah ++++++.

    But it would be Nice if python provides native support for Session Handling, JSON — like XML-RPC Standard Environment for RPC + WSGI and future technologies. for Easy Web Development

    Many shared hosting servers do not allow persistent processes. They kill a script if it runs for more than 3 minutes. This frameworks do not explain (or make life easier) for someone who as only cgi and ftp. Do you know any way to code easier/faster in this circumstances ? Osvaldo

    CgiScripts (last edited 2014-04-16 06:53:27 by DaleAthanasias )

    Источник

    Python CGI example

    CGI is abbreviated as Common Gateway Interface in Python, which is a block of benchmarks to explain the exchange of data among the web server and a script. A CGI program is written by an HTTP server as the user input is entered through the HTML . In other words, it is a collection of procedures that are used to build a dynamic interaction between the client and the server application. When a client uses any element or sends a request to the web browser, that CGI executes a particular request, and the result or the output is sent back to the webserver.

    CGI concept

    Whenever we use a hyperlink in our websites and click on that hyperlink to visit a particular website or a URL, the browser interacts with the Hypertext transfer protocol (HTTP) web. The web server then uses a URL and searches a similar filename. If the match is found, then the file is sent back. If the file is not found in the second case, an error message is displayed that we have entered the wrong file name.

    A web browser is used in taking a reply from the web server and shows the content. This can set the server of HTTP so that whenever we request a specific file, then this file must be executed instead of sending it back. Whatever is the content of that file is executed as a program and is sent back to the browser to display the file. For python, these codes are declared as Python scripts.

    If you are willing to execute Python scripts on the web, you have to study how to execute python as a CGI script.

    Apache webserver configuration for CGI

    Configuration of the server is needed to get our CGI scripts. This will be done by setting a directory as Script Alias Directive. You may use other options by downloading “xamp” on your system. The “scriptAlias” is used to map between “filesystem” paths and the URLs. The script alias uses a way of having the effect of making the target directory as that it contains only the CGI scripts. Setting a directory as “scriptAlias” Directive is essential because it recognizes that all the files that exist in the directory are CGI scripts. Usually, a script Alias looks like the below link in “HTTP.conf” of the apache web server.

    Run CGI from a specific directory

    To prepare a specific directory to display the CGI script, you need to use the following link.

    Where ‘dir’ is the directory of your own choice, by using the above-mentioned configuration, you need to specify the following to tell the extensions of the server of CGI files you are willing to run.

    This piece of information plays an important role in telling Apache to execute files with .CGI and .PL extensions as CGI.

    IIS web server for CGI configuration

    The operating system we are up to is Windows 10. That is similar to the windows server 2007 and 2008 as well. Whatever the operating system is, you must have a running python interpreter on the Windows Operating system.

    For this purpose, go to the taskbar. Open ‘control panel’. Now click on the ‘Programs’. Select the desired option of the windows feature. A small window is opened having the title of ‘windows features’. Navigate to the Internet ‘Internet’s information services’. Now go to the ‘application Development Feature’ and move down to the check box of CGI. To continue, select ‘ok’.

    Now go to the start and then move towards the IIS manager window. Here go to the ‘Default website’ on the left panel. Right-click ‘default website’ and then click the ‘Add application’.

    Now in the ‘Alias’ text box, enter the name. i.e., “PythonApp”. And in the ‘physical path’ add the path where the “Pythonapp” application is saved. Then click “ok” to proceed further.

    After the configuration of the webserver to run python as CGI, we now try to run a simple code on the webserver. Some points should be followed before starting.

    • Make sure that the Python code doesn’t contain any syntax errors.
    • Make sure your file has, read, write, executed for administrator privileges so that it can be modified wherever you are going to run this file, either on Windows, Linux, or Unix.

    Execute First sample file

    Use HTML code for the input fields.

    We have shared a small piece of the code of form-making only. This coding is to create a text file and a button for the submission of data. You have to write the coding of all essentials of HTML. We have entered the name that will appear on the python when we run the code.

    Now moving towards the python code.

    # print(«Name of the user is:»,name)

    Now let us explain the above written Python code. Firstly, we need to import the basic modules for the execution.

    “Cgitb.enable()” helps you when nothing good is happening. Or you find any error. But one thing that should be mentioned here is that it does not guide you if you encounter EOF issues or any sort of syntax error. It has some other purposes.

    Now we have used text files of the CGI module in the form. The name will be extracted by HTML form using:

    A print command is used to display the text we have entered in the textbox on the HTML page. This command will take the data from the getvalue(‘fname’) function. A variable is used here to store the fetched value.

    CGI programming advantages

    There are many useful aspects of CGI programming. Some of them are mentioned here.

    • These programs are language-independent.
    • The CGI programs can work on any web server.
    • They are portable and can increase the dynamic communication between web applications.

    Some of the disadvantages also need some attention.

    • These programs are hard to debug as they are too complex.
    • The processing time required is very long.
    • Mostly the data is not stored in the cache memory.

    Conclusion

    ‘python CGI example’ is an article of a practically creating connection between the server and the client. This is done by undergoing various steps and procedures both at the server and client sides. We have used a simple example to print a name on Python when it has been entered into the browser. An additional feature of HTML is added for creating the input sample page. I hope our intentions of making you aware of CGI usage will work.

    About the author

    Aqsa Yasin

    I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.

    Источник

    Читайте также:  For each key value php
Оцените статью