CGI Programming in Python
Last Updated :
18 Mar, 2024
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.
- CGI is the standard for programs to interface with HTTP servers.
- 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">😀 Happy</label>
<input type='checkbox' name='happy' id="happy" />
<!-- Sad checkbox with label and ID 'sad' -->
<label class="checkbox-label" for="sad">😢 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.
Similar Reads
Getting Started with Python Programming Python is a versatile, interpreted programming language celebrated for its simplicity and readability. This guide will walk us through installing Python, running first program and exploring interactive codingâall essential steps for beginners.Install PythonBefore starting this Python course first, y
3 min read
Last Minute Notes (LMNs) - Python Programming Python is a widely-used programming language, celebrated for its simplicity, comprehensive features, and extensive library support. This "Last Minute Notes" article aims to offer a quick, concise overview of essential Python topics, including data types, operators, control flow statements, functions
15+ min read
Python Input Methods for Competitive Programming Python is an amazingly user-friendly language with the only flaw of being slow. In comparison to C, C++, and Java, it is quite slower. In online coding platforms, if the C/C++ limit provided is x. Usually, in Java time provided is 2x, and in Python, it's 5x. To improve the speed of code execution fo
6 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
How to Create a Programming Language using Python? In this article, we are going to learn how to create your own programming language using SLY(Sly Lex Yacc) and Python. Before we dig deeper into this topic, it is to be noted that this is not a beginner's tutorial and you need to have some knowledge of the prerequisites given below. PrerequisitesRou
7 min read
Calling Python from C | Set 2 Prerequisite: Calling Python from C | Set 1 A reference to an existing Python callable needs to be passed in, to use this function. To do that there are many ways like â simply writing C code to extract a symbol from an existing module or having a callable object passed into an extension module. Cod
3 min read
Calling Python from C | Set 1 In this article, we will mainly focus on safe execution of a Python callable from C, returning a result back to C and writing C code that needs to access a Python function as a callback. The code below focuses on the tricky parts that are involved in calling Python from C. Code #1 : [Step 1 and 2] O
2 min read
Python Built in Functions Python is the most popular programming language created by Guido van Rossum in 1991. It is used for system scripting, software development, and web development (server-side). Web applications can be developed on a server using Python. Workflows can be made with Python and other technologies. Databas
6 min read
Introduction to Python3 Python is a high-level general-purpose programming language. Python programs generally are smaller than other programming languages like Java. Programmers have to type relatively less and indentation requirements of the language make them readable all the time. Note: For more information, refer to P
3 min read
Python Functions Python Functions is a block of statements that return the specific task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it ov
11 min read