Python Programming (136 Blogs) Become a Certified Professional
AWS Global Infrastructure

Data Science

Topics Covered
  • Business Analytics with R (26 Blogs)
  • Data Science (20 Blogs)
  • Mastering Python (83 Blogs)
  • Decision Tree Modeling Using R (1 Blogs)
SEE MORE

How To Best Utilize Python CGI In Day To Day Coding?

Published on Sep 30,2019 3.1K Views

14 / 62 Blog from Python Fundamentals

Python is one of the most versatile programming languages available in the market today. The main reason for popularity of Python is the great number of features it brings to the table as well as its versatility across multiple platforms. One of the features of the Python programming system that we get asked about most is the Python CGI and thus in this article we will talk more about the Python CGI, its uses and how you can implement it in your day to day coding.

Following pointers will be covered in this article,

Let us get started then

Python CGI

What Is CGI?

CGI or Common Gateway Interface is the industry accepted acronym for a set method that is used to define how information is exchanged between the web server and a custom script. As of date, the CGI scripts are officially maintained by the NCSA. 

Using CGI in Python

As mentioned in an earlier paragraph, CGI is a manner of writing a program that has the ability to exchange data through a web server that is running on another web server. 

One of the most important things to note, while writing a CGI program on the Python interface is that CGI programs are written to dynamically generate web pages that not only take input from users but also display the output at the same time. 

Example 

To understand the concept of CGI programming in Python, let us take a look at the following example. 

Note: You need to have apache2 already installed in order to execute the following example. This program named ‘hello.py’ will by default run on host 127.0.0.1. 

#!/usr/bin/python3 
# Importing the 'cgi' module 
import cgi 
print("Content-type: text/htmlrnrn") 
print("<html><body>")&nbsp;
print("

<h1> Hello Program! </h1>

")&nbsp;
# Using the inbuilt methods&nbsp;
form = cgi.FieldStorage()&nbsp;
if form.getvalue("name"):&nbsp;
name = form.getvalue("name")&nbsp;
print("

<h1>Hello" +name+"! Thanks for using my script!</h1>

")&nbsp;
if form.getvalue("happy"):&nbsp;
print("
 Yayy! I'm happy too! 
")&nbsp;
if form.getvalue("sad"):&nbsp;
print("
 Oh no! Why are you sad? 
")&nbsp;
# Using HTML input and forms method&nbsp;
print("

<form method='post' action='hello2.py'>
")&nbsp;
print("
Name: <input type='text' name='name' />
")&nbsp;
print("<input type='checkbox' name='happy' /> Happy")&nbsp;
print("<input type='checkbox' name='sad' /> Sad")&nbsp;
print("<input type='submit' value='Submit' />")&nbsp;
print("</form")&nbsp;
print("</body></html>") 

Output

Output -Python CGI - Edureka

Let us see what is the structure of a Python CGI program,

Structure of a Python CGI Program 

Now that you know what a CGI program looks like in Python, let us take a closer look at the structure of the same.

  1. The output of a CGI script written in Python must contain two sections separated by a blank line. 
  2. The first section will contain the headers that describe and the second section will contain the kind of data that will be used during the execution of the script. 

To understand this, take a look at the example below.

print ("Content-Type : text/html")
# then comes the rest hyper-text documents
print ("<html>")
print ("<head>")
print ("<title>My First CGI-Program </title>")
print ("<head>")
print ("<body>")
print ("
<h3>This is HTML's Body section </h3>
")
print ("</body>")
print ("</html>")

Output

Output -Python CGI - Edureka

In order to use the CGI module in Python, you first need to import it into the Python IDLE. The syntax to do the same is as follows. 

import cgitb

cgitb.enable()

By using the above code, you are basically triggering the formation of a special exception handler that has the ability to display any run time error within the browser at the time of execution. 

Legend of Syntaxes

When scripting a CGI program in Python take note of the following commonly used syntaxes. 

HTML

  1. Content or Type: text/html
  2. Location: URL
  3. Expires: Date
  4. Content Length: N
  5. Set Cookie: String

Let us take a look at the final bit of this Python CGI article that is Environment Variables,

CGI Environment Variables 

Along with the HTMl syntaxes shared above, you also need to make a note about the commonly used CGI environment variables. 

  1. CONTENT_TYPE: This is used to describe data and type of the content. 
  2. CONTENT_LENGTH: This is mainly used in Post to define the length of a query or information.
  3. HTTP_COOKIE: If in a certain situation, the user has set a cookie, then this is used to return the same.
  4. HTTP_USER_AGENT: If you need to view the type of browser the user is currently using, then this variable will be used. 
  5. REMOTE_HOST: This is used to define the host name of the visitor.
  6. PATH_INFO: This is used to define the path of a CGI script.
  7. REMOTE_ADDR: If you need to define the IP address of the visitor, then you can make use of this variable. 
  8. REQUEST_METHOD: This is used to make a request either via POST or GET.

This brings us to the end of this article.

To get in-depth knowledge on Python along with its various applications, you can enroll here for live online training with 24/7 support and lifetime access.

Got a question for us? Mention them in the comments section of this article and we will get back to you.

Upcoming Batches For Python Programming Certification Course
Course NameDateDetails
Python Programming Certification Course

Class Starts on 23rd March,2024

23rd March

SAT&SUN (Weekend Batch)
View Details
Python Programming Certification Course

Class Starts on 20th April,2024

20th April

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

How To Best Utilize Python CGI In Day To Day Coding?

edureka.co