The Wayback Machine - https://web.archive.org/web/20241007102608/https://www.geeksforgeeks.org/cgi-programming-python/
Open In App

CGI Programming in Python

Last Updated : 18 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.



Similar Reads

Emerging technologies and trends in CGI programming
In the ever-evolving global generation, Computer-Generated Imagery (CGI) programming isn't any exception to the rule of thumb. CGI has come a prolonged way due to the fact its inception, and it continues to strengthen at a mind-blowing pace. This article explores the growing era and trends in CGI programming, shedding light on the thoughts, and ste
7 min read
What is CGI in Python ?
CGI stands for Common Gateway Interface in Python which is a set of standards that explains how information or data is exchanged between the web server and a routine script. This interface is used by web servers to route information requests supplied by a browser or we can say that CGI is customary for external gateway programs to interface with in
3 min read
GET and POST in Python CGI
In this article, we will explore the GET and POST methods in CGI. In Python, the Common Gateway Interface (CGI) plays an important role as it enables and helps in the creation of dynamic web pages. It basically allows Python scripts to be executed and run on a web server in response to a client's HTTP request. if you are learning networking for the
5 min read
How to create a simple CGI script?
In this article, we will explore how to create a simple CGI (Common Gateway Interface) script on a Windows machine but before that, we need some basic ideas about these technologies ( CGI Script, HTTP, Web Server ).CGI Script: A CGI script is a program that runs on a web server and generates dynamic web content. It's often used for processing web f
2 min read
Historical context and evolution of CGI.
When you click on any of the links on the webpage, your browser contacts the HTTP web server and demands the URL that is, the filename, and the web server passes the URL and looks for the filename, if it finds that file, it will send it back to the browser otherwise sends an indicating message that you have requested a wrong file. Then, the web bro
12 min read
CGI vs Client-Side Scriting ( Javascript)
In the ever-evolving world of web development, two fundamental technologies play a crucial role in enhancing user experiences and enabling dynamic web applications: CGI (Common Gateway Interface) and Client-Side Scripting, often powered by JavaScript. These technologies serve different purposes and have distinct characteristics. In this blog, we'll
3 min read
How to handle form data in CGI Scripts?
In this article, we'll guide you through the process of creating a registration form in HTML and then using a CGI script to fetch and display the submitted user data in the form of a card, along with a success message. Registration forms are a fundamental component of many web applications, allowing users to provide essential information for access
4 min read
How to Create Form using CGI script
HTML forms are a fundamental part of web development, allowing users to input data and interact with web applications. Web developers often use Common Gateway Interface (CGI) scripts to process and send the data submitted through these forms. In this article, we'll explain what Python CGI scripts are and guide you through how we can create a form u
3 min read
How to generate dynamic content with CGI?
In this article, we will explore how we can generate dynamic content with CGI (Common Gateway Interface) script on a Windows machine. We will create a webpage in which various user interactions can be performed, dynamic data is been displayed as per user input. CGI Script: A CGI script is nothing but a program that is executed on the web server and
4 min read
Handling File Uploads via CGI
In this article, we will explore how we can handle file uploads via CGI (Common Gateway Interface) script on Windows machines. We will develop a form in which there will be the functionality of uploading the file, when the user uploads the file and submits the form, the data is been passed to the CGI script and the file that is uploaded will get st
6 min read
What is the role of CGI in Web development?
CGI stands for common gateway interface. It is an interface that enables the web server to process a user's HTTPS request by executing a program. It executes a program that resides on the server to process data to produce the relevant dynamic content. When a client gives a request or input, this data is passed to the CGI script as an environment va
6 min read
How To Enable or Disable CGI Scripts in Apache?
This article will guide you on how to enable or disable CGI scripts in Apache. Configuring CGI scripts in Apache is a crucial aspect of managing dynamic content generation on web servers. The Common Gateway Interface (CGI) provides a standardized protocol for executing programs, allowing websites to produce dynamic output. Whether enabling or disab
4 min read
How to generate webpages using CGI scripts?
In this article, we will explore the process of generating webpages using CGI scripts. Furthermore, we will discuss the importance of CGI script implementation in facilitating dynamic content creation. Additionally, we'll delve into the intricacies of linking one page to another by creating multiple pages within Python CGI scripts, ensuring a seaml
4 min read
How to generate basic HTML output using CGI scripts?
In this article, we will explore the process of generating basic HTML output using CGI scripts. Specifically, we will focus on creating a simple HTML web page using Python. The objective is to provide a step-by-step walkthrough, detailing the entire process of creating and utilizing CGI scripts to generate HTML content within a web environment. Wha
3 min read
How to Execute SQL queries from CGI scripts
In this article, we will explore the process of executing SQL queries from CGI scripts. To achieve this, we have developed a CGI script that involves importing the database we created. The focus of this discussion will be on writing code to execute SQL queries in Python CGI scripts. The initial step involves creating a database, and it's worth noti
5 min read
How CGI Scripts recieve data from HTML forms?
In this article, we will see how we can revive the data from HTML forms in CGI Scripts (Common Gateway Interface). We will perform the demonstration on a Windows Operating System machine. We will create a basic HTML form and a CGI script using Python, which will handle the data revived from the HTML form. Related Concepts CGI Script: A CGI script i
5 min read
Object Oriented Programming in Python | Set 2 (Data Hiding and Object Printing)
Prerequisite: Object-Oriented Programming in Python | Set 1 (Class, Object and Members) Data hiding In Python, we use double underscore (Or __) before the attributes name and those attributes will not be directly visible outside. Python Code class MyClass: # Hidden member of MyClass __hiddenVariable = 0 # A member method that changes # __hiddenVari
3 min read
Python - Fastest Growing Programming Language
There was a time when the word "Python" meant a particularly large snake but now it is a programming language that is all the rage!!! According to the TIOBE Index, Python is the fourth most popular programming language in the world currently and this extraordinary growth is only set to increase as observed by Stack Overflow Trends. So the question
5 min read
Difference between Python and Lua Programming Language
Python Python is one of the most popular and powerful scripting languages that works nowadays. It is a high-level interpreted programming language. It is a very simple scripting language and very easy to learn as compared to other languages. Python programming language is best for both scripting applications and as standalone programs along with th
3 min read
Programming Paradigms in Python
Paradigm can also be termed as a method to solve some problems or do some tasks. A programming paradigm is an approach to solve the problem using some programming language or also we can say it is a method to solve a problem using tools and techniques that are available to us following some approach. There are lots of programming languages that are
4 min read
Python | Implementing Dynamic programming using Dictionary
Dynamic Programming is one way which can be used as an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of subproblems so that we do not have to re-compute them when needed later. This simple opti
3 min read
Comparison of Python with Other Programming Languages
Python is an easily adaptable programming language that offers a lot of features. Its concise syntax and open-source nature promote readability and implementation of programs which makes it the fastest-growing programming language in current times. Python has various other advantages which give it an edge over other popular programming languages su
3 min read
Mathematics Tricks For Competitive Programming In Python 3
Here are some of the exciting features that Python 3.8 provides for programmers in competitive programming. These new features are related to some math functions and algorithms that are frequently used by competitive programmers. The implementation of these features has the time complexity which is the same in case of a program when implemented fro
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. PrerequisitesRough knowledge about compiler design.Basic understan
7 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 language in current times. Features of PythonEasy to c
4 min read
Network Programming Python - HTTP Clients
The request from the client in HTTP protocol reaches the server and fetches some data assuming it to be a valid request. This response from the server can be analyzed by using various methods provided by the requests module. Some of the ways below provide information about the response sent from the server to the Python program running on the clien
2 min read
Incremental Programming in Python
In incremental systems, every measurement refers to a previously dimensioned position (point-to-point). Incremental dimensions are the distances between two adjacent points. An incremental movement moves A distance based on your current position. Start Small - First of all, start your program small and kept that working instead of writing many line
2 min read
Draw house using Turtle programming in Python
Prerequisite: Turtle Programming in Python “Turtle” is a Python feature like a drawing board, which lets us command a turtle to draw all over it! ”turtle” comes packed with the standard Python package and need not be installed externally. Step 1: Import turtle and math module in Python. import turtle import math Step 2: Choose a background color fo
2 min read
Network Programming Python - HTTP Server
HTTP Web Server is simply a process which runs on a machine and listens for incoming HTTP Requests by a specific IP and Port number, and then sends back a response for the request. Python has a built-in webserver provided by its standard library, can be called for simple client-server communication. The http.server and socketserver are the two main
3 min read
Network Programming Python - HTTP Requests
HTTP stands for HyperText Transfer Protocol, which works on the client-server machine. In most cases, the web browser acts as the client, and the computer which hosts the website acts as a server. Python provides the requests module to play with HTTP requests. The requests module plays a major role in HTTP requests, apart from simple request and th
2 min read
Article Tags :
Practice Tags :