Open In App

CGI Programming in Python

Last Updated : 18 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

What is CGI?

Common Gateway Interface (also known as CGI) is not a kind of language but just a

specification(set of rules)

that helps to establish a dynamic interaction between a web application and the browser (or the client application). The CGI programs make possible

communication between client and web servers

. Whenever the client browser sends a request to the webserver the CGI programs send the output back to the web server based on the input provided by the client-server.

  1. CGI is the standard for programs to interface with HTTP servers.
  2. CGI programming is written dynamically generating webpages that respond to user input or webpages that interact with software on the server

Working of CGI

When a request is made by the client-server to the webserver, the CGI uses

external script files

to handle such requests. These files could be written in any language. The main objective of these script files is to retrieve the data from the database quickly and more efficiently. These scripts convert the retrieved data into an Html format that sends the data to these web servers in Html formatted page.

Install apache2 on your system can we will run ‘hello_process.py’ on host ‘127.0.0.1’

It is recommended to have basic knowledge of HTML before trying this example.

hello_process.py

In this code:

  • The script is written in Python and is intended to be executed as a CGI script.
  • It sends an HTTP header with the content type set to HTML.
  • The HTML content starts with a centered layout.
  • A green heading with the text “GeeksforGeeks” is displayed.
  • The script parses form data submitted via a POST request.
  • If the “name” field is present, it retrieves the value and displays a personalized greeting.
  • If the “happy” checkbox is selected, it displays a happy message with an emoji.
  • If the “sad” checkbox is selected, it displays a sad message with an emoji.
  • The HTML document is closed at the end.
  • The script essentially generates a web page that greets users by name, acknowledges their happiness, and asks why they are sad if they select the respective checkboxes.
Python
#!/usr/bin/env python
# Importing the 'cgi' module
import cgi

# Send an HTTP header indicating the content type as HTML
print("Content-type: text/html\n\n")

# Start an HTML document with center-aligned content
print("<html><body style='text-align:center;'>")

# Display a green heading with text "GeeksforGeeks"
print("<h1 style='color: green;'>GeeksforGeeks</h1>")

# Parse form data submitted via the CGI script
form = cgi.FieldStorage()

# Check if the "name" field is present in the form data
if form.getvalue("name"):
    # If present, retrieve the value and display a personalized greeting
    name = form.getvalue("name")
    print("<h2>Hello, " + name + "!</h2>")
    print("<p>Thank you for using our script.</p>")

# Check if the "happy" checkbox is selected
if form.getvalue("happy"):
    # If selected, display a message with a happy emoji
    print("<p>Yayy! We're happy too! ????</p>")

# Check if the "sad" checkbox is selected
if form.getvalue("sad"):
    # If selected, display a message with a sad emoji
    print("<p>Oh no! Why are you sad? ????</p>")

# Close the HTML document
print("</body></html>")

then we create the html file

hello_form.html

this HTML code creates a web page with the following elements:

  • We have an HTML page with a green “GeeksforGeeks” heading.
  • There’s a form that uses the POST method to submit data to the ‘hello_process.py’ script.
  • The form contains a text input field for the name and two checkboxes for “Happy” and “Sad.”
  • CSS is used to style the page elements, including fonts, alignment, and spacing.
  • Labels and IDs are used to associate labels with form elements for better accessibility.
  • Comments are added in the code to explain each section’s purpose.
  • This code creates a simple HTML form with a green heading and checkboxes for “Happy” and “Sad.” When submitted, the form sends the data to ‘hello_process.py’ for further processing.
HTML
<!DOCTYPE html>
<html>
<head>
    <!-- Set the title of the web page -->
    <title>Hello Form</title>
    <style>
        /* Add some basic CSS for styling */
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
            text-align: center;
        }
        h1 {
            font-size: 24px;
            color: green; /* Change the heading color to green */
        }
        form {
            padding: 20px;
            margin: 0 auto;
            width: 300px;
        }
        p {
            margin: 10px 0;
        }
        input[type='text'], input[type='checkbox'], input[type='submit'] {
            display: block;
            margin: 5px auto;
        }
        .checkbox-label {
            display: inline-block; /* Display checkboxes inline */
            margin-right: 10px; /* Add spacing between checkboxes and labels */
        }
    </style>
</head>
<body>
    <!-- Green heading with text "GeeksforGeeks" -->
    <h1>GeeksforGeeks</h1>
    <!-- Form with method 'post' and action 'hello_process.py' -->
    <form method='post' action='hello_process.py'>
        <!-- Name input field -->
        <p><label for="name">Name:</label> <input type='text' name='name' id="name" /></p>
        <!-- Happy checkbox with label and ID 'happy' -->
        <label class="checkbox-label" for="happy">&#128512; Happy</label>
        <input type='checkbox' name='happy' id="happy" />
        <!-- Sad checkbox with label and ID 'sad' -->
        <label class="checkbox-label" for="sad">&#128546; Sad</label>
        <input type='checkbox' name='sad' id="sad" />
        <!-- Submit button -->
        <input type='submit' value='Submit' />
    </form>
</body>
</html>

Output :






Some advantages of CGI are discussed as below:

1 They are portable and can work on almost any web server and operating system. 2 They are language-independent. 3 They are quite scalable programs in nature which means they can perform both simple and complex tasks. 4 CGIs enhance dynamic communication in web applications. 5They also aid in making businesses more profitable by decreasing development and maintenance costs.

Some disadvantages of CGI are as below:

1 The interpreter has to evaluate a CGI script every time the program is initiated this creates a lot of traffic as there are too many requests from the side of the client-server. 2 Programming and designing of CGI programs is very complex and ambiguous. 3 CGI programs may compromise server security as most of them are free and easily available making them quite vulnerable. This article is contributed by

Harsh Wardhan Chaudhary (Intern)

. If you like GeeksforGeeks and would like to contribute, you can also write an article using

write.geeksforgeeks.org

or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads