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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Similar Reads
Functional Programming in Python
Functional programming is a programming paradigm in which we try to bind everything in a pure mathematical functions style. It is a declarative type of programming style. Its main focus is on " what to solve" in contrast to an imperative style where the main focus is "how to solve". It uses expressi
10 min read
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,
3 min read
Python vs Other Programming Languages
Python is a general-purpose, high level programming language developed by Guido van Rossum in 1991. It was structured with an accentuation on code comprehensibility, and its syntax allows programmers to express their concepts in fewer lines of code which makes it the fastest-growing programming lang
4 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
Simple Calculator in Python Socket Programming
In this article, we are going to know how to make a simple calculator in Python socket programming. Prerequisite: Socket Programming in Python. First, we will understand the basics of Python socket programming. Socket programming is used to set up a communication channel between two nodes on a netwo
4 min read
Python print() function
The python print() function as the name suggests is used to print a python object(s) in Python as standard output. Syntax: print(object(s), sep, end, file, flush) Parameters: Object(s): It can be any python object(s) like string, list, tuple, etc. But before printing all objects get converted into s
2 min read
Getting Started with Competitive Programming in Python
Python is a great option for programming in Competitive Programming. First off, its easy-to-understand and concise grammar enables quicker development and simpler debugging. The huge standard library of Python offers a wide range of modules and functions that can be used to effectively address progr
11 min read
Python Main Function
Main function is like the entry point of a program. However, Python interpreter runs the code right from the first line. The execution of the code starts from the starting line and goes line by line. It does not matter where the main function is present or it is present or not. Since there is no mai
5 min read
Multithreading in Python
This article covers the basics of multithreading in Python programming language. Just like multiprocessing , multithreading is a way of achieving multitasking. In multithreading, the concept of threads is used. Let us first understand the concept of thread in computer architecture. What is a Process
8 min read