× Python Introduction What is Python Python Features Python History Python Applications Python Install Python Path Python Example Execute Python Keywords Constant Variable Statements & Comments Python I/O and Import Operators UnaryBinaryTernary Unary Operators Unary Minus Binary Operators Arithmetic Operators Assignment Operators Relational Operators Logicaloperators Bitwise Operator Ternary Operators Control Statements in Python conditonal Statements IF if else Else If Nested if Switch For loop Nested For Loop While Loop Nested while Loop Unconditonal Statemets Continue Break Pass FUNCTIONS Python Function Function Argument Python Recursion Anonymous Function Python Modules NATIVE DATATYPES Python List Python Numbers Python Tuple Python String Python Set Python Dictionary OOPS PRINCIPALS Encapsulation Class Variable Method Object Or Instance CreationMethod Calling OOPS Syntax And Explanation DATA ABSTRACTION Constructor Inheritance 1.Single or simple Inheritance 2.Multilevel Inheritance 3.Hierarchical Inheritance 4.Multiple Inheritance 5.Hybrid Inheritance Operator Overloading File Operation Python Directory Python Exception Python - Multithreading Python - Database Access Python - CGI Python - Reg Exp Python - Date Python - XML Processing Python - GUI
  • iconPython Online Training In Andhra Pradesh and Telangana
  • icon9010519704

Opening Hours :7AM to 9PM

Python CGI


What is CGI
CGI (Common Gateway Interface) is a way for a web server to execute scripts or programs via a web browser. In Python, you can use CGI to create dynamic web pages that can interact with a web server, database, or other programs.
To create a CGI program in Python, you need to follow these steps:
1.Write your Python script: This should be a normal Python script that you would run from the command line. It should contain all the necessary logic and functions to generate the desired output.
2.Save your script in the correct location: On most web servers, the CGI scripts are stored in a special directory, such as "/cgi-bin". You will need to save your script in this directory.
3.Make your script executable: You will need to set the permissions on your script so that it can be executed by the web server. This is usually done using the "chmod" command, which stands for "change mode".
4.Create a form in your HTML file: If you want to allow users to input data into your CGI program, you will need to create a form in your HTML file. This form should contain various input elements, such as text fields and buttons, that allow users to enter data.
5.Add a "submit" button to your form: This button will allow users to submit their data to your CGI program. When the button is clicked, the web server will execute your CGI script and pass the user-submitted data to it as input.
6.Use the "cgi" module to process the user-submitted data: In your Python script, you can use the "cgi" module to access the user-submitted data and process it as needed. This module provides functions for parsing form data and accessing individual form elements.
Here is an example of a simple CGI program in Python that displays a form and processes the user-submitted data:
#!C:\Users\msate\AppData\Local\Programs\Python\Python311\python.exe

import cgi, cgitb 
print("Content-type: text/html")
print()
print("<html>")
print("<body>")
print("<h1>Hello cgi</h1>")
print("</body>")
print("</html>")    
    
#!C:\Users\msate\AppData\Local\Programs\Python\Python311\python.exe

import cgi
form = cgi.FieldStorage()
name = form.getvalue('name')

print("Content-type: text/html")
print()
print("<html>")
print("<body>")
print("<h1>Hello, {}!</h1>".format(name))
print("</body>")
print("</html>")

This script displays a form that asks for the user's name, and then displays a greeting using the entered name. When the user submits the form, the script uses the "cgi" module to retrieve the user's name from the form data and display it in the greeting.

Key Points

  • cgi

Image
Simple CGI Program
Steps: Open Python editor
Write CGI Program
Save CGI Program in the following location
Goto C:\xampp\htdocs
Create a Project Folder
C:\xampp\htdocs\Sateesh
FileName: first.py After saving CGI file
Run CGI Program
1.Open xampp Server
2.Sert tomact and mysql Server
3.go to web Browser
4.type Localhost in address bar and type \ project folder name(http://localhost/sateesh)
5.Click on your Python File
#!C:\Users\msate\AppData\Local\Programs\Python\Python311\python.exe

# Import modules for CGI handling 
import cgi, cgitb 
x=10
y=20
z=x+y
print ("Content-type:text/html\r\n\r\n")
print ("<html>")
print ("<head>")
print ("<title>Hello - Second CGI Program</title>")
print ("</head>")
print ("<body>")
print("<h1>addition is %d</h1>"% z)
print ("</body>")
print ("</html>")


Output:
30
CGI Program with HTML
Step -1: Create html file
Second.html
Step -2: Create cgi file
Second.py
Second.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="second.py" method="get">
First Number<input type="text" name="fno" ><br>
Second Number<input type="text" name="sno" ><br>
<input type="submit" value="add me">
</form>

</body>
</html>

 
second.py
 #!C:\Users\msate\AppData\Local\Programs\Python\Python311\python.exe

# Import modules for CGI handling 
import cgi, cgitb 

print ("Content-type:text/html\r\n\r\n")
print ("<html>")
print ("<head>")
print ("<title>Hello - Second CGI Program</title>")
print ("</head>")
print ("<body>")

# Create instance of FieldStorage 
form = cgi.FieldStorage() 
x=int(form.getvalue("fno"))
y=int(form.getvalue("sno"))
z=x+y

print("<h1>addition is %d</h1>"% z)
print ("</body>")
print ("</html>")


Output:
24
cgi Program with HTML and Database
Step -1: Create html file
third.html
Step -2: Create CGI file
third.py
Step -3: Create table in Database:
create table calc (fno int,sno int,res int);

third.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="third.py" method="get">
First Number<input type="text" name="fno" ><br>
Second Number<input type="text" name="sno" ><br>
<input type="submit" value="add me">
</form>

</body>
</html>

third.cgi
#!C:\Users\msate\AppData\Local\Programs\Python\Python311\python.exe

# Import modules for CGI handling 
import cgi, cgitb
import pymysql

print ("Content-type:text/html\r\n\r\n")
print ("<html>")
print ("<head>")
print ("<title>Hello - Second CGI Program</title>")
print ("</head>")

# Create instance of FieldStorage 
form = cgi.FieldStorage() 
x=int(form.getvalue("fno"))
y=int(form.getvalue("sno"))
z=x+y

# Open database connection
db = pymysql.connect(host="localhost",user="root",password = "",db="Rain",)
# prepare a cursor object using cursor() method
cursor = db.cursor()
sql="INSERT INTO calc(fno, sno, res) VALUES ('%d', '%d', '%d' )" %  (x, y, z)

try:
    s=cursor.execute(sql)
    if(s==1):
        print("<h1>Successfully Inserted </h1>'")
    else:
         print("<h1> Insertion Failed </h1>")
    db.commit()
except Exception as e:
    db.rollback()

# disconnect from server
db.close()

print ("<body>")
print("<h1>addition is %d</h1>"% z)
print ("</body>")
print ("</html>")


Output:
CGI Program -4

Registration Form:


Step -1 : reg.html
Step -2 : reg.py
Step -3 : reg Table in Database
    
    
create table reg(
        username varchar(20),
        password varchar(20),
        gender varchar(20),
        location varchar(20),
        l1 varchar(20),
        l2 varchar(20),
        l3 varchar(20) ,
        address varchar(20)
        );
reg.html
    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="reg.py" method="post">

Username:<input type="text" name="uname" id="uname"><br>
Password:<input type="password" name="pass" id="pass"><br>
gender<input type="radio" name="gender" id="gender" value="male">Malee
<input type="radio" name="gender" id="gender" value="female">Femalee<br>

location:<select name="loc">

<option value="hyd">Hyderabad</option>
<option value="del">Delhi</option>
<option value="che">Chennai</option>

</select>
<br>
Languages:<input type="checkbox" name="telugu" value="telugu" id="telugu">Teluguu
<input type="checkbox" name="English" value="English" id="English">"English"
<input type="checkbox" name="hindi" value="hindi" id="hindi">hindi

Address:<textarea rows="20" cols="20" id="adder" name="addr"></textarea>
<br>
<input type="submit" value="sign up">
</form>

</body>
</html>





reg.py

#!C:\Users\msate\AppData\Local\Programs\Python\Python311\python.exe

# Import modules for CGI handling 
import cgi, cgitb
import pymysql

print ("Content-type:text/html\r\n\r\n")
print ("<html>")
print ("<head>")
print ("<title>Hello - Second CGI Program</title>")
print ("</head>")

# Create instance of FieldStorage 
form = cgi.FieldStorage() 
username=form.getvalue("uname")
password=form.getvalue("pass")
gender=form.getvalue("gender")
location=form.getvalue("loc")
l1=form.getvalue("telugu")
l2=form.getvalue("english")
l3=form.getvalue("hindi")
address=form.getvalue("addr")


# Open database connection
db = pymysql.connect(host="localhost",user="root",password = "",db="Rain",)
# prepare a cursor object using cursor() method
cursor = db.cursor()
sql="INSERT INTO reg(username,password,gender,location,l1,l2,l3,address) VALUES ('%s', '%s', '%s' ,'%s', '%s', '%s','%s', '%s')" %  (username, password,gender,location,l1,l2,l3,address)

try:
    s=cursor.execute(sql)
    if(s==1):
        print("<h1>Successfully Inserted </h1>'")
    else:
         print("<h1> Insertion Failed </h1>")
    db.commit()
except Exception as e:
    print("<h1> Insertion Failed  %s</h1>" % e)
    db.rollback()

# disconnect from server
db.close()

print ("<body>")
print("<h1>addition is %d</h1>"% z)
print ("</body>")
print ("</html>")


Output:
CGI Program -5

Login Form(Without redirect)

Steps:
Step 1: login.html
Step 2: login.py
Login html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="login.py" method="post">

Username<input type="text" name="uname"><br>
Password<input type="password" name="pass"><br>
<input type="submit" value="login">



</form>
</body>
</html>

 
login.py
    
#!C:\Users\msate\AppData\Local\Programs\Python\Python311\python.exe

# Import modules for CGI handling 
import cgi, cgitb
import pymysql
print ("Content-type:text/html\r\n\r\n")
print ("<html>")
print ("<head>")
print ("<title>Hello - Second CGI Program</title>")
print ("</head>")
print ("<body>")

# Create instance of FieldStorage 
form = cgi.FieldStorage() 

x = form.getvalue('uname')
y  = form.getvalue('pass')
dx=""
dy=""

# Open database connection
db = pymysql.connect(host="localhost",user="root",password = "",db="Rain",)
# prepare a cursor object using cursor() method
cursor = db.cursor()
sql = "SELECT * FROM reg where username='%s' and password='%s'" %(x,y)
       
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Fetch all the rows in a list of lists.
   results = cursor.fetchall()
   for row in results:
      dx = row[0]
      dy = row[1]
   if(x==dx and y==dy):
        print("<h1>Login Success</h1>")
   else:
        print("<h1>login failed</h1>")
    
      
except Exception as e:
   print ("<h1>unable to fecth data  </h1>",e)

    
print ("</body>")
print ("</html>")






success.html
    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<h1>login success</h1>

<form action="view.py" method="post">

<input type="submit" value="view my details">
</form>

<form action="viewtable.py" method="post">

<input type="submit" value="view in table">
</form>

<form action="viewlist.py" method="post">

<input type="submit" value="view in list">
</form>

<form action="viewtext.py" method="post">

<input type="submit" value="view in textbox">
</form>

<form action="edit.py" method="post">

<input type="submit" value="edit my details">
</form>



</body>
</html>


    

Output:
CGI Program -6

Login Form(With redirect)

Steps:
Step 1: login.html
Step 2: success.html
Step 3: login.py
Step 1: login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="login.cgi" method="post">

Username<input type="text" name="uname"><br>
Password<input type="password" name="pass"><br>
<input type="submit" value="login">

</form>
</body>
</html>

 
Step 2: success.html
    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<h1>login success</h1>

</body>
</html>


    
Step 3: login.py
#!C:\Users\msate\AppData\Local\Programs\Python\Python311\python.exe

# Import modules for CGI handling 
import cgi, cgitb
import pymysql
print ("Content-type:text/html\r\n\r\n")
print ("<html>")
print ("<head>")
print ("<title>Hello - Second CGI Program</title>")
print ("</head>")
print ("<body>")

# Create instance of FieldStorage 
form = cgi.FieldStorage() 

x = form.getvalue('uname')
y  = form.getvalue('pass')
dx=""
dy=""

# Open database connection
db = pymysql.connect(host="localhost",user="root",password = "",db="Rain",)
# prepare a cursor object using cursor() method
cursor = db.cursor()
sql = "SELECT * FROM reg where username='%s' and password='%s'" %(x,y)
       
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Fetch all the rows in a list of lists.
   results = cursor.fetchall()
   for row in results:
      dx = row[0]
      dy = row[1]
   if(x==dx and y==dy):
        print ("<meta http-equiv='refresh' content='0;url=success.html'")
   else:
        print("<h1>login failed</h1>")
    
      
except Exception as e:
   print ("<h1>unable to fecth data  </h1>",e)

    
print ("</body>")
print ("</html>")


Output:
Login Program(with using cookies)
Step 1: login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="login.py" method="post">

Username<input type="text" name="uname"><br>
Password<input type="password" name="pass"><br>
<input type="submit" value="login">

</form>
</body>
</html>

 
Step 2: success.html
    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<h1>login success</h1>

</body>
</html>


    
Step 3: login.py
    
#!C:\Users\msate\AppData\Local\Programs\Python\Python311\python.exe

# Import modules for CGI handling 
import cgi, cgitb
import pymysql
from http import cookies
# Create instance of FieldStorage 
form = cgi.FieldStorage() 


x = form.getvalue('uname')
y  = form.getvalue('pass')
dx=""
dy=""

#cookies creation
c = cookies.SimpleCookie()
c['sk2'] = x
c['sk3'] = y
print( c)

print ("Content-type:text/html\r\n\r\n")
print ("<html>")
print ("<head>")
print ("<title>MSK Technologies</title>")
print ("</head>")
print ("<body>")


# Open database connection
db = pymysql.connect(host="localhost",user="root",password = "",db="Rain",)
# prepare a cursor object using cursor() method
cursor = db.cursor()
sql = "SELECT * FROM reg where username='%s' and password='%s'" %(x,y)
       
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Fetch all the rows in a list of lists.
   results = cursor.fetchall()
   for row in results:
      dx = row[0]
      dy = row[1]
   if(x==dx and y==dy):
        print ("<meta http-equiv='refresh' content='0;url=success.html'")
   else:
        print("<h1>login failed</h1>")
    
      
except Exception as e:
   print ("<h1>unable to fecth data  </h1>",e)

    
print ("</body>")
print ("</html>")

Output:

CGI Program


Success Page

Key Points

  • What is cgi
  • What is Sessions
  • What is Cookies

Image
cgi Program -7

Success.html

                                       
success.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h1>cgi login success</h1> <form action="view.py" method="post"> <input type="submit" value="view my details"> </form> <form action="viewtable.py" method="post"> <input type="submit" value="view in table"> </form> <form action="viewlist.py" method="post"> <input type="submit" value="view in list"> </form> <form action="viewtextbox.py" method="post"> <input type="submit" value="view in textbox"> </form> <form action="edit.py" method="post"> <input type="submit" value="edit my details"> </form> </body> </html>
Output:
cgi Program -8
view.py
View Data
View Program(without using cookies)
#!C:\Users\msate\AppData\Local\Programs\Python\Python311\python.exe

# Import modules for CGI handling 
import cgi, cgitb
import pymysql
print ("Content-type:text/html\r\n\r\n")
print ("<html>")
print ("<head>")
print ("<title>MSK Technologies</title>")
print ("</head>")
print ("<body>")

# Create instance of FieldStorage 
form = cgi.FieldStorage() 

# Open database connection
db = pymysql.connect(host="localhost",user="root",password = "",db="Rain",)
# prepare a cursor object using cursor() method
cursor = db.cursor()

sql = "SELECT * FROM reg "
       
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Fetch all the rows in a list of lists.
   results = cursor.fetchall()
   for row in results:
      username = row[0]
      password = row[1]
      gender = row[2]
      location = row[3]
      l1 = row[4]
      l2 = row[5]
      l3 = row[6]
      address = row[7]
      print("%s ,%s ,%s ,%s ,%s ,%s ,%s ,%s " %(username,password,gender,location,l1,l2,l3,address))
      print("<br>")
    
      
except Exception as e:
   print ("<h1>unable to fecth data  </h1>",e)

    
print ("</body>")
print ("</html>")

Output:
View Program(with using cookies)
#!C:\Users\msate\AppData\Local\Programs\Python\Python311\python.exe

# Import modules for CGI handling 
import cgi, cgitb
import pymysql
import os
from http import cookies

print ("Content-type:text/html\r\n\r\n")
print ("<html>")
print ("<head>")
print ("<title>MSK Technologies</title>")
print ("</head>")
print ("<body>")

# Create instance of FieldStorage 
form = cgi.FieldStorage() 

# Open database connection
db = pymysql.connect(host="localhost",user="root",password = "",db="Rain",)
# prepare a cursor object using cursor() method
cursor = db.cursor()

x=""
y=""
cookie = cookies.SimpleCookie()
cookie_string = os.environ.get('HTTP_COOKIE')
if not cookie_string:
   print ('<p>First visit or cookies disabled</p>')   
else:
   cookie.load(cookie_string)
   x = cookie['sk2'].value
   y = cookie['sk3'].value
sql = "SELECT * FROM reg where username='%s' and password='%s'" %(x,y)
       
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Fetch all the rows in a list of lists.
   results = cursor.fetchall()
   for row in results:
      username = row[0]
      password = row[1]
      gender = row[2]
      location = row[3]
      l1 = row[4]
      l2 = row[5]
      l3 = row[6]
      address = row[7]
      print("%s ,%s ,%s ,%s ,%s ,%s ,%s ,%s " %(username,password,gender,location,l1,l2,l3,address))
      print("<br>")
except Exception as e:
   print ("<h1>unable to fecth data  </h1>",e)
print ("</body>")
print ("</html>")





Output:
CGI Program -9
viewtable.py
View Data in html Table
Company Contact Country
Alfreds Futterkiste Maria Anders Germany
Centro comercial Moctezuma Francisco Chang Mexico
View Data in html Table Program(without using cookies)
#!C:\Users\msate\AppData\Local\Programs\Python\Python311\python.exe

# Import modules for CGI handtdng 
import cgi, cgitb
import pymysql
print ("Content-type:text/html\r\n\r\n")
print ("<html>")
print ("<head>")
print ("<title>MSK Technologies</title>")
print ("</head>")
print ("<body>")

# Create instance of FieldStorage 
form = cgi.FieldStorage() 

# Open database connection
db = pymysql.connect(host="localhost",user="root",password = "",db="Rain",)
# prepare a cursor object using cursor() method
cursor = db.cursor()

sql = "SELECT * FROM reg "
       
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Fetch all the rows in a tdst of tdsts.
   results = cursor.fetchall()
   print("<table border=1>")
   for row in results:
      username = row[0]
      password = row[1]
      gender = row[2]
      location = row[3]
      l1 = row[4]
      l2 = row[5]
      l3 = row[6]
      address = row[7]
      print("<tr>")
      print("<td>%s</td>" % username)
      print("<td>%s</td>" % password)
      print("<td>%s</td>" % gender)
      print("<td>%s</td>" % location)
      print("<td>%s</td>" % l1)
      print("<td>%s</td>" % l2)
      print("<td>%s</td>" % l3)
      print("<td>%s</td>" % address)
      print("</tr>")

   print("</table>")
except Exception as e:
   print ("<h1>unable to fecth data  </h1>",e)
   
print ("</body>")
print ("</html>")

Output:
View Data in html Table Program(with using cookies)
#!C:\Users\msate\AppData\Local\Programs\Python\Python311\python.exe

# Import modules for CGI handtdng 
import cgi, cgitb
import pymysql
import os
from http import cookies
print ("Content-type:text/html\r\n\r\n")
print ("<html>")
print ("<head>")
print ("<title>MSK Technologies</title>")
print ("</head>")
print ("<body>")

# Create instance of FieldStorage 
form = cgi.FieldStorage() 

# Open database connection
db = pymysql.connect(host="localhost",user="root",password = "",db="Rain",)
# prepare a cursor object using cursor() method
cursor = db.cursor()

x=""
y=""
cookie = cookies.SimpleCookie()
cookie_string = os.environ.get('HTTP_COOKIE')
if not cookie_string:
   print ('<p>First visit or cookies disabled</p>')   
else:
   cookie.load(cookie_string)
   x = cookie['sk2'].value
   y = cookie['sk3'].value
sql = "SELECT * FROM reg where username='%s' and password='%s'" %(x,y)

try:
   # Execute the SQL command
   cursor.execute(sql)
   # Fetch all the rows in a tdst of tdsts.
   results = cursor.fetchall()
   print("<table border=1>")
   for row in results:
      username = row[0]
      password = row[1]
      gender = row[2]
      location = row[3]
      l1 = row[4]
      l2 = row[5]
      l3 = row[6]
      address = row[7]
      print("<tr>")
      print("<td>%s</td>" % username)
      print("<td>%s</td>" % password)
      print("<td>%s</td>" % gender)
      print("<td>%s</td>" % location)
      print("<td>%s</td>" % l1)
      print("<td>%s</td>" % l2)
      print("<td>%s</td>" % l3)
      print("<td>%s</td>" % address)
      print("</tr>")

   print("</table>")
except Exception as e:
   print ("<h1>unable to fecth data  </h1>",e)
print ("</body>")
print ("</html>")




Output:
cgi Program -10
viewlist.py
View Data in html List
  • Coffee
  • Tea
  • Milk
View Data in html List Program(without and cookies)
#!C:\Users\msate\AppData\Local\Programs\Python\Python311\python.exe

# Import modules for CGI handling 
import cgi, cgitb
import pymysql
print ("Content-type:text/html\r\n\r\n")
print ("<html>")
print ("<head>")
print ("<title>MSK Technologies</title>")
print ("</head>")
print ("<body>")

# Create instance of FieldStorage 
form = cgi.FieldStorage() 

# Open database connection
db = pymysql.connect(host="localhost",user="root",password = "",db="Rain",)
# prepare a cursor object using cursor() method
cursor = db.cursor()

sql = "SELECT * FROM reg "
       
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Fetch all the rows in a list of lists.
   results = cursor.fetchall()
   for row in results:
      username = row[0]
      password = row[1]
      gender = row[2]
      location = row[3]
      l1 = row[4]
      l2 = row[5]
      l3 = row[6]
      address = row[7]
      print("<ol type='1'>")
      print("<li>%s</li>" % username)
      print("<li>%s</li>" % password)
      print("<li>%s</li>" % gender)
      print("<li>%s</li>" % location)
      print("<li>%s</li>" % l1)
      print("<li>%s</li>" % l2)
      print("<li>%s</li>" % l3)
      print("<li>%s</li>" % address)
      print("</ol>")
except Exception as e:
   print ("<h1>unable to fecth data  </h1>",e)
print ("</body>")
print ("</html>")

Output:
View Data in html List Program(with using cookies)
#!C:\Users\msate\AppData\Local\Programs\Python\Python311\python.exe

# Import modules for CGI handling 
import cgi, cgitb
import pymysql
import os
from http import cookies
print ("Content-type:text/html\r\n\r\n")
print ("<html>")
print ("<head>")
print ("<title>MSK Technologies</title>")
print ("</head>")
print ("<body>")

# Create instance of FieldStorage 
form = cgi.FieldStorage() 

# Open database connection
db = pymysql.connect(host="localhost",user="root",password = "",db="Rain",)
# prepare a cursor object using cursor() method
cursor = db.cursor()

x=""
y=""
cookie = cookies.SimpleCookie()
cookie_string = os.environ.get('HTTP_COOKIE')
if not cookie_string:
   print ('<p>First visit or cookies disabled</p>')   
else:
   cookie.load(cookie_string)
   x = cookie['sk2'].value
   y = cookie['sk3'].value
sql = "SELECT * FROM reg where username='%s' and password='%s'" %(x,y)
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Fetch all the rows in a list of lists.
   results = cursor.fetchall()
   for row in results:
      username = row[0]
      password = row[1]
      gender = row[2]
      location = row[3]
      l1 = row[4]
      l2 = row[5]
      l3 = row[6]
      address = row[7]
      print("<ol type='1'>")
      print("<li>%s</li>" % username)
      print("<li>%s</li>" % password)
      print("<li>%s</li>" % gender)
      print("<li>%s</li>" % location)
      print("<li>%s</li>" % l1)
      print("<li>%s</li>" % l2)
      print("<li>%s</li>" % l3)
      print("<li>%s</li>" % address)
      print("</ol>")
except Exception as e:
   print ("<h1>unable to fecth data  </h1>",e)
print ("</body>")
print ("</html>")

Output:
cgi Program -11
viewtextbox.py
View Data in html TextBox
View Data in html TextBox Program(without using and cookies)
#!C:\Users\msate\AppData\Local\Programs\Python\Python311\python.exe

# Import modules for CGI handtdng 
import cgi, cgitb
import pymysql
print ("Content-type:text/html\r\n\r\n")
print ("<html>")
print ("<head>")
print ("<title>MSK Technologies</title>")
print ("</head>")
print ("<body>")

# Create instance of FieldStorage 
form = cgi.FieldStorage() 

# Open database connection
db = pymysql.connect(host="localhost",user="root",password = "",db="Rain",)
# prepare a cursor object using cursor() method
cursor = db.cursor()

sql = "SELECT * FROM reg "
       
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Fetch all the rows in a tdst of tdsts.
   results = cursor.fetchall()
   print("<table border=1>")
   for row in results:
      username = row[0]
      password = row[1]
      gender = row[2]
      location = row[3]
      l1 = row[4]
      l2 = row[5]
      l3 = row[6]
      address = row[7]
      print("<tr>")
      print("<input type='text' name='uname' value='%s'><br>" % username)
      print("<input type='text' name='pass' value='%s'><br>"  % password)
      print("<input type='text' name='gender' value='%s'> <br>" % gender)
      print("<input type='text' name='loc' value='%s'> <br>" % location)
      print("<input type='text' name='l1' value='%s'> <br>" % l1)
      print("<input type='text' name='l2' value='%s'> <br>" % l2)
      print("<input type='text' name='l3' value='%s'> <br>" % l3)
      print("<input type='text' name='address' value='%s'> <br>" % address)
      print("</tr>")

   print("</table>")
except Exception as e:
   print ("<h1>unable to fecth data  </h1>",e)
print ("</body>")
print ("</html>")

Output:
View Data in html TextBox Program(with using cookies)

#!C:\Users\msate\AppData\Local\Programs\Python\Python311\python.exe

# Import modules for CGI handtdng 
import cgi, cgitb
import pymysql
import os
from http import cookies
print ("Content-type:text/html\r\n\r\n")
print ("<html>")
print ("<head>")
print ("<title>MSK Technologies</title>")
print ("</head>")
print ("<body>")

# Create instance of FieldStorage 
form = cgi.FieldStorage() 

# Open database connection
db = pymysql.connect(host="localhost",user="root",password = "",db="Rain",)
# prepare a cursor object using cursor() method
cursor = db.cursor()

x=""
y=""
cookie = cookies.SimpleCookie()
cookie_string = os.environ.get('HTTP_COOKIE')
if not cookie_string:
   print ('<p>First visit or cookies disabled</p>')   
else:
   cookie.load(cookie_string)
   x = cookie['sk2'].value
   y = cookie['sk3'].value
  
sql = "SELECT * FROM reg where username='%s' and password='%s'" %(x,y)
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Fetch all the rows in a tdst of tdsts.
   results = cursor.fetchall()
   print("<table border=1>")
   for row in results:
      username = row[0]
      password = row[1]
      gender = row[2]
      location = row[3]
      l1 = row[4]
      l2 = row[5]
      l3 = row[6]
      address = row[7]
      print("<tr>")
      print("<input type='text' name='uname' value='%s'><br>" % username)
      print("<input type='text' name='pass' value='%s'><br>"  % password)
      print("<input type='text' name='gender' value='%s'> <br>" % gender)
      print("<input type='text' name='loc' value='%s'> <br>" % location)
      print("<input type='text' name='l1' value='%s'> <br>" % l1)
      print("<input type='text' name='l2' value='%s'> <br>" % l2)
      print("<input type='text' name='l3' value='%s'> <br>" % l3)
      print("<input type='text' name='address' value='%s'> <br>" % address)
      print("</tr>")

   print("</table>")
except Exception as e:
   print ("<h1>unable to fecth data  </h1>",e)
print ("</body>")
print ("</html>")




Output:
cgi Program -12
edit.py
#!C:\Users\msate\AppData\Local\Programs\Python\Python311\python.exe

# Import modules for CGI handtdng 
import cgi, cgitb
import pymysql
import os
from http import cookies
print ("Content-type:text/html\r\n\r\n")
print ("<html>")
print ("<head>")
print ("<title>MSK Technologies</title>")
print ("</head>")
print ("<body>")

# Create instance of FieldStorage 
form = cgi.FieldStorage() 

# Open database connection
db = pymysql.connect(host="localhost",user="root",password = "",db="Rain",)
# prepare a cursor object using cursor() method
cursor = db.cursor()

x=""
y=""
cookie = cookies.SimpleCookie()
cookie_string = os.environ.get('HTTP_COOKIE')
if not cookie_string:
   print ('<p>First visit or cookies disabled</p>')   
else:
   cookie.load(cookie_string)
   x = cookie['sk2'].value
   y = cookie['sk3'].value
sql = "SELECT * FROM reg where username='%s' and password='%s'" %(x,y)

try:
   # Execute the SQL command
   cursor.execute(sql)
   # Fetch all the rows in a tdst of tdsts.
   results = cursor.fetchall()
  
   for row in results:
      username = row[0]
      password = row[1]
      gender = row[2]
      location = row[3]
      l1 = row[4]
      l2 = row[5]
      l3 = row[6]
      address = row[7]
      print("<form action='update.py' method='post'>")
      print("UserName:<input type='text' name='uname' value='%s'><br>" % username)
      print("Password:<input type='text' name='pass' value='%s'><br>"  % password)
      print("Gender:<input type='text' name='gender' value='%s'> <br>" % gender)
      print("Location: <input type='text' name='loc' value='%s'> <br>" % location)
      print("L1:<input type='text' name='l1' value='%s'> <br>" % l1)
      print("L2:<input type='text' name='l2' value='%s'> <br>" % l2)
      print("L3:<input type='text' name='l3' value='%s'> <br>" % l3)
      print("Address:<input type='text' name='address' value='%s'> <br>" % address)
      print("<input type='submit' value='click'>")
      print("</form>")

except Exception as e:
   print ("<h1>unable to fecth data  </h1>",e)

print ("</body>")
print ("</html>")





 
Output:
CGI Program -13
update.py
Update
                                    
 #!C:\Users\msate\AppData\Local\Programs\Python\Python311\python.exe

# Import modules for CGI handtdng 
import cgi, cgitb
import pymysql
import os
from http import cookies
print ("Content-type:text/html\r\n\r\n")
print ("<html>")
print ("<head>")
print ("<title>MSK Technologies</title>")
print ("</head>")
print ("<body>")

# Create instance of FieldStorage 
form = cgi.FieldStorage() 

# Open database connection
db = pymysql.connect(host="localhost",user="root",password = "",db="Rain",)
# prepare a cursor object using cursor() method
cursor = db.cursor()

gender=form.getvalue("gender")
location=form.getvalue("loc")
l1=form.getvalue("l1")
l2=form.getvalue("l2")
l3=form.getvalue("l3")
address=form.getvalue("address")

x=""
y=""
cookie = cookies.SimpleCookie()
cookie_string = os.environ.get('HTTP_COOKIE')
if not cookie_string:
   print ('<p>First visit or cookies disabled</p>')   
else:
   cookie.load(cookie_string)
   
   x = cookie['sk2'].value
   y = cookie['sk3'].value

sql = "update reg set gender='%s', location='%s',l1='%s',l2='%s',l3='%s',address='%s' where username='%s' and password='%s'" %(gender,location,l1,l2,l3,address,x,y)
try:
    s=cursor.execute(sql)
    if(s==1):
        print("<h1>Successfully Updated </h1>'")
    else:
         print("<h1> Updation Failed </h1>")
    db.commit()
except Exception as e:
    print("<h1> Updation Failed  %s</h1>" % e)
    db.rollback()
print ("</body>")
print ("</html>")
 
Output: