0% found this document useful (0 votes)
7 views30 pages

MODULE 4

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 30

Module IV

Database Programming
1. DATABASE PROGRAMMING

Python allows us to connect to various databases though database interfaces. Python's


database interface is DB-API (Data Base- Application Programming Interface). We can
choose the database which we want to connect to Python. Python DB-API supports a large
number of databases like Oracle, MS-SQL server 2000, MySQL, mSQL, Sybase etc. For
using each database we need to download separate DB-API modules.

The API includes the following steps which include importing the API module, acquiring a
connection with the database, issuing SQL statements and stored procedures and closing the
connection. Here we are using all the concepts and examples using MySQL. MySQL is an
open source database. For connecting to MySQL database, we need pymysql, which is an
interface connecting MySQL and Python. Before establishing a connection between Python
and MySQL, we should make sure that pymysql is installed in our machine.

How to install pymysql


To install it first copy the path of script folder inside your python folder and paste it in
command prompt as cd path (copied). And then use the command pip3 install pymysql.

2. CONNECTING TO A DATABASE

Before connecting to a database, following things should be done to assure the right
connectivity.

1. Create a database called SAMPLE in MySQL.

2. The user id and password used to access SAMPLE database is "root" and "" respectively.

3. Create a table STUDENT in SAMPLE.

4. The table STUDENT has fields ROLLNO, NAME, AGE, COURSE, GRADE.

The following code shows how to connect MySQL database with Python.

Example program

import pymysql

# Open database connection


1
db = pymysql. connect (host='localhost',user='root', password="",db="SAMPLE")

# prepare a cursor object using Cursor () method

cursor = db. cursor ()

# execute SQL query using execute () method.

cursor. execute ("SELECT VERSION () ")

# Fetch a single row using fetchone () method.

data = cursor.fetchone ()

print ("Database version: ", data)

# disconnect from server

db.close ()

While running this script, it is producing the following output in Windows machine.

Output

Database version: 5.6.36-log

3. CREATING TABLES

Once a connection is successfully established, we can create the tables. Creation of tables,
insertion, updation and deletion operations are performed in Python with the help of execute
() statement. The following example shows how to create a table in MySQL from Python.

Example program

import pymysql

# Open database connection

db = pymysql . connect (host='localhost',user='root', password="",db="SAMPLE")

# prepare a cursor object using cursor () method

cursor = db.cursor()

# Create table as per requirement

2
sql = """create table dept(deptno int, dept_name char(20),location char(25))"""

cursor.execute (sql)

db.commit()

#disconnect from server

db. close ()

The program creates a table called DEPT with fields DEPENO, DEPT NAME and
LOCATION. The SQL statement for creating the table is stored in sql and the sql is passed to
execute () method for creating the table.

4. INSERT OPERATION

Once a table is created, we need to insert values to the table. The values can be inserted using
the INSERT statement of SQL. The following example shows an example for insert
operation.

Example program

import pymysql

# Open database Connection

db = pymysql . connect (host='localhost',user='root', password="",db="SAMPLE")

# prepare a cursor object using cursor() method

Cursor = db.Cursor( )

#prepare SQL query to INSERT a record into the database.

Sql= """insert into dept values(1001,'CSA','First floor')"""

cursor. execute (sql)

db. commit ()

#disconnect from server

db.close ()

A record with specified values will be inserted into the DEPT table.

3
5. UPDATE OPERATION

UPDATE operation is done to modify existing values available in the table. We can update
one or more records at the same time. The following example shows how to update records in
a table from Python.

import pymysql

#Open database connection

db = pymysql . connect (host='localhost',user='root', password="",db="SAMPLE")

# prepare a cursor object using cur8or () method

cursor = db, cursor ()

# Prepare SQL query to UPDATE records into a table.

sql= """update dept set location='Ground floor' where deptno=1001"""

cursor.execute (sql)

db. commit ()

# disconnect from server

db.close ()

The above example updates the location of CSA department from First Floor to Ground
Floor. If there is more than one record with the satisfied condition, then all those records will
updated.
6. DELETE OPERATION

DELETE operation is required when we want to delete some undesired or unwanted records
from a table. We can specify DELETE operation with or without conditions. The following
example shows how to delete records from a table.

import pymysql

# Open database connection

db=pymysql.connect(host='localhost',user='root',password="",db="SAMPLE")

# prepare a cursor object using cursor () method

cursor = db. cursor ()


4
# Prepare SQL query to DELETE records from a table.

sql = """delete from dept1 where location=”Ground Floor”

cursor.execute (sql)

db. commit ()

# disconnect from server

db.close ()

The above example will delete all the records with location Ground Floor.

7. READ OPERATION

READ operation is used to fetch desired records from a database. There are several methods
for fetching records from a database. Once a connection is established, we can make queries
to a database. The following methods are used in READ operation.

1. fetchone(): It fetches the next row of a query result set. A result set is an object that is
returned when a cursor object is used to query a table.

Sample program

import pymysql

# Open database Connection

db=pymysql.connect(host='localhost',user='root',password="",db="SAMPLE")

# prepare a cursor object using cursor () method

cursor =db. cursor ()

#prepare SQL query

sql= "””SELECT LOCATION FROM DEPT”””

cursor. execute (sql)

# Fetches the next Record. In this case first Record

row= cursor . fetchone ()

if row:
print ("Location: " , row [0] )
5
# disconnect from server

db.close ()

Output

Location: Ground Floor

2. fetchall (): It fetches all the rows in a result set. If some rows have already been extracted
from the result set, then it retrieves the remaining rows from the result set.

Example program

import pymysql

# Open database Connection

db=pymysql.connect(host='localhost',user='root',password="",db="Sample")

# prepare a cursor object using cursor () method

cursor=db.cursor()

# Prepare SQL query

sql = "SELECT LOCATION FROM DEPT"

cursor. execute (sql)

# Fetches all the records.

rows = cursor. fetchall ()

for row in rows:

print ("Location: ", row [0] )

# disconnect from server

db.close ()

Output

Location: Ground Floor

Location: First Floor

Location: Second Floor


6
3. rowcount(): This is a read-only attribute and returns the number of rows that were affected
by the execute() method.
Example program

import pymysql

# Open database connection

db=pymysql.connect(host='localhost',user='root',password="",db="Sample")

cursor=db.cursor()

# Prepare SQL query

sql = "SELECT LOCATION FROM DEPT"

cursor.execute (sql)

# Displays number of records.

numrows = cursor.rowcount

print ("Number of Records:", numrows.rowcount)

# disconnect from server

db.close ()

Output

Number of Records:3

8. TRANSACTION CONTROL

A transaction is a logical unit of work that contains one or more SQL statements. A
transaction is an atomic unit. The effects of all the SQL statements in a transaction can be
either all committed (applied to the database) or all rolled back (undone from the database).
Transaction is a mechanism to ensure data consistency. Transaction ensures 4 properties
generally referred to as ACID properties.

Atomicity: ensures that all operations within the work unit are completed successfully;
otherwise, the transaction is aborted at the point of failure, and previous operations are rolled
back to their former state.

Consistency: ensures that the database properly change states upon a successfully committed

7
transaction.

Isolation: enable transactions to operate independently and transparent to each other.

Durability: ensures that the result or effect of a committed transaction persists in case of a
system failure.

9. COMMIT OPERATION

The COMMIT command is the transactional command used to save changes invoked by a
transaction to the database. The COMMIT command saves all transactions to the database
since the last COMMIT or ROLLBACK command. The syntax for a commit statement is
db.commit().
10. ROLLBACK OPERATION

The ROLLBACK command is the transactional command used to undo transactions that have
not already been saved to the database. The ROLLBACK command can only be used to undo
transactions since the last COMMIT or ROLLBACK command was issued. The syntax is db.
rollback ().

Example Program for COMMIT and ROLLBACK

import pymysql

# Open data

db=pymysql.connect(host='localhost',user='root',password="",db="Sample")

# prepare a cursor object using cursor () method

cursor=db.cursor()

# Prepare SQL query to INSERT a record into the database.

Sql=”””INSERT INTO DEPT (DEPTNO, DEPT NAME, LOCATION) VALUES (10, 'Sales'
Chennai' ) "””

cursor. execute (sql)

# Commit changes in the database

db. commit ()

except:

8
db.rollback()

db.close ()

Dol1back in case there is any error

db. rollback ()

# disconnect from server

In the above example, commit() statement makes changes to the database permanently.

11. DISCONNECTING FROM A DATABASE

A close() method is called to disconnect from the database. The syntax for closing is
db.close(). If the connection to a database is closed by the user with the close() method, any
outstanding transactions are rolled back by the database. However, instead of depending on
any of database lower level implementation details, our application would be better to call
commit or rollback explicitly.
12. EXCEPTION HANDLING IN DATABASES

There are many Sources of errors in databases. A few examples are a syntax error in an
executed SQL statement, a connection failure, or calling the fetch method for an already
canceled or finished statement handle. The database API defines a number of errors that must
exist in each database module. The following Table 10.1 list the Exceptions and their
descriptions related to databases.

9
13. ITERATORS

There are many types of objects which can be used with a for loop. We can use a for loop for
iterating through a list, string, dictionary or a file. These are called iterable objects.

Example program

for element in [1, 2, 3]:

print (element)

for element in (1, 2, 3) :

print (element)

for key in{ 'one':1, 'two' :2}:

print (key)

for char in "123 ":

print (char)

for line in open ("myfile. txt"):

print (line, end=’ ‘ )

This style of access is clear, concise, and convenient. The use of iterators pervades and
unifies Python. Behind the scenes, the for statement calls iter() on the container object. The

function returns an iterator object that defines the method next () which raises a
StopIteration exception which tells the for loop to terminate.

Python iterator object must implement two special methods, iter () and next (),
collectively called the iterator protocol. An object is called iterable if we can get an iterator
from it. Most of the built in containers in python like list, tuple, string etc. are iterables. The
iter() function (which in turn calls the iter () method) returns an iterator from them.

Example program

>>> X= iter([1,2,3])

>>> X

<list_iterator object at 0x000001F721BCD760>


10
>>> X. next ()

>>> X. next ()

>>> X. next ()

>>>X. next ()

Traceback (most recent call last):

File "<pyshell#10>", line 1, in <module>

x. next ()

StopIteration

The built-in function iter takes an iterable object and returns an iterator. Iterators have several
advantages:

✓ Cleaner code
✓ Iterators can work with infinite sequences
✓ Iterators save resources

By saving system resources we mean that when working with iterators, we can get the next
element in a sequence without keeping the entire dataset in memory.

14. DATA TYPES THAT SUPPORT ITERATORS

Iterators can be materialized as lists or tuples by using the list() or tuple() constructor
functions. The following program shows how a list can be converted to an iterator and then to
materialize to a tuple.

Example Program

list= [1, 2, 3]

iterator=iter (list)

11
t=tuple (iterator)

print (t)

Output

(1,2,3)

Sequence unpacking also supports iterators. If we know an iterator will return N elements,
We can unpack them into an N-tuple.

15. CGI PROGRAMMING

The common gateway interface (CGI) is a standard way for a Web server to pass a Web
user's request to an application program and to receive data back to forward to the user. When
the user requests a Web page (for example, by clicking on a highlighted word or entering a
Web site address), the server sends back the requested page. However, when a user fills out a
form on a Web page and sends it in, it usually needs to be processed by an application
program. The Web server typically passes the form information to a small application
program that processes the data and may send back a confirmation message. This method or
convention for passing data back and forth between the server and the application is called
the common gateway interface (CGI). It is part of the Web's Hypertext Transfer Protocol
(HTTP).

CGI is a set of standards that define how information is exchanged between the web server
and a custom script. To understand the concept of CGI, let us see what happens when we
click a hyper link to browse a particular web page or URL.

a) The browser contacts the HTTP web server and demands for the URL, i.e., filename.

b) Web Server parses the URL and looks for the filename. If it finds that file then sends it
back to the browser, otherwise sends an error message indicating that you requested a wrong
file.

c) Web browser takes response from web server and displays either the received file or error
message.

It is possible to set up the HTTP server so that whenever a file in a certain directory is
requested that file is not sent back. Instead it is executed as a program, and whatever that
program outputs is sent back for the browser to display. This function is called the Common
Gateway Interface or CGI and the programs are called CGI scripts. These CGI programs
12
can be a Python script, PERL script, Shell script, C or C++ program, etc.

How to run a CGI Program

First make sure you have installed xampp in your system. Now open xampp control panel.
Click config button of apache server and choose Apache (httpd.conf). Now a notepad file is
opened. Search Addh or Addhandler and type .py as shown below. Save the file and restart
your apache server to run the cgi scripts.

To run a cgi program make a folder inside the htdocs and save the python file with cgi script.
Now open the browser and type http://localhost/foldername/filename.py. Example:
http://localhost/Mary/demo5.py

A Simple CGI Program


Before you proceed with CGI Programming, make sure that your Web Server supports CGI
and it is configured to handle CGI Programs. All the CGI Programs to be executed by the
HTTP server are kept in a pre-configured directory. This directory is called CGI Directory
and by convention it is named as /var/www/cgi-bin. By convention, CGI handles have
extension as .cgi, but you can keep your files with pvthon extension .py as well.

Example Program

print("Content-type:text/html")

print()

print("html")

print("<head>")

print("<title> First CGI Program </title>")

print("</head>")

print("<body>")

print("<h2> Welcome to CGI programming </h2>")

print("</body>")

print("</html>")

Output

13
Welcome to CGI Programming

There is one important and extra feature available which is first line to be printed content-
type:text/html followed by a blank line. This line is sent back to the browser and it specifies
the content type to be displayed on the browser screen.

16. HTTP HEADERS

All HTTP headers will be in the following form.

HTTP Field Name: Field Content

Example

Content-type: text/html

A list of commonly used HTTP headers is shown in Table 14.1.

17. ENVIRONMENT VARIABLES

Environment variables are a series of hidden values that the web server sends to every CGI
program we run. Our program can parse them and use the data they send. Environment
variables are stored in a hash named %ENV:. These variables play an important role while
writing any CGI program. The Table 14.2 shows a list of CGI environment variables with
14
their description.

18. FORMS

A form is an area that can contain form elements. Form elements allow the user to enter
information (like text fields, textarea fields, drop-down menus, radio buttons, checkboxes etc)
in a form. A form is defined with the <form> tag.

Example Program

login.py saved inside the folder in htdocs


15
#!C:\Users\JOSE\AppData\Local\Programs\Python\Python38\python.exe

#import modules for CGI handling

import cgi, cgitb

# create instance of fieldstorage

form=cgi.FieldStorage()

#get data from fields

username=form.getvalue('username')

password=form.getvalue('password')

print("Content-type:text/html")

print()

print("<html>")

print("<head>")

print("<title> Username and Password </title>")

print("</head>")

print("<body>")

print("<h2> Hello! Username is %s and Password is %s </h2>" %(username,password))

print("</body>")

print("</html>")

login.html saved inside the folder in htdocs

<form action="login.py" method="get">

Username: <input type="text" name="username"> <br/>

Password: <input type="password" name="password"/> <br/>

<input type="submit" value="submit" />

</form>

16
Note: Ensure both files in same folder inside the htdocs.

Output

19. GET METHOD

The above program has used the method GET. The GET method is the default method to pass
information from the browser to web server and it produces a long string that appears in our
browser’s box. Never use GET method if we have password or other sensitive information to
pass to the server. The GET method has size limitation. Only 1024 characters can be sent in a
request string. The GET method sends information using QUERY_STRING header and will
be accessible in our CGI program through QUERY_STRING environment variable.

We can pass information by simply concatenating key and value pairs along with any URL or
can use HTML <form> tags to pass information using GET method.

20. POST METHOD

POST method is considered more reliable for passing information to a CGI program. This
prepare the information in exactly the same way as GET method, but instead of send it as a
text string after a question mark(?) in the URL it sends it as a separate message. This message
17
comes into the CGI script in the form of the standard input. The same login.py in above GET

method is used for the POST method also. The following code shows the script for POST
<form action="login.py" method="post">

Username: <input type="text" name="username"> <br/>

Password: <input type="password" name="password"/> <br/>

<input type="submit" value="submit" />

</form>

Here is the actual output of the above form. Enter the user name and password and then click
submit button to see the result.

Output

21. RADIO BUTTONS

Radio buttons are used when only one option is required to be selected. Below is radio.py
script to handle input given by web browser for radio button.

radio.py saved inside the folder in htdocs

#!C:\Users\JOSE\AppData\Local\Programs\Python\Python38\python.exe

#import modules for CGI handling

18
import cgi, cgitb

# create instance of fieldstorage

form=cgi.FieldStorage()

#get data from fields

if form.getvalue('sex'):

sex=form.getvalue('sex')

else:

sex="Not set"

print("Content-type:text/html")

print()

print("<html>")

print("<head>")

print("<title> Radio Button CGI Program </title>")

print("</head>")

print("<body>")

print("<h2> Selected sex is %s </h2>" %sex)

print("</body>")

print("</html>")

radio.html saved inside the folder in htdocs

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

<input type="radio" name="sex" value="Male"/> Male

<input type="radio" name="sex" value="Female"/> Female <br/>

<input type="submit" value="Select" />

</form>

19
Note: Ensure both files in same folder inside the htdocs.

Output

22. DROP DOWN BOX

Drop Down Box is used when we have many options available but only one or two will be
selected. Only one option will be displayed and to view all options, we need to click on the
drop down box. This can be used instead of radio buttons. The above script radio.py is
modified to implement drop down box in a Web browser.

dropdownbox.py saved inside the folder in htdocs

#!C:\Users\JOSE\AppData\Local\Programs\Python\Python38\python.exe

#import modules for CGI handling

import cgi, cgitb

# create instance of fieldstorage

form=cgi.FieldStorage()

#get data from fields

if form.getvalue('sex'):

sex=form.getvalue('sex')

else:

20
sex="Not entered"

print("Content-type:text/html")

print()

print("<html>")

print("<head>")

print("<title> Dropdown Box CGI Program </title>")

print("</head>")

print("<body>")

print("<h2> Selected sex is %s </h2>" %sex)

print("</body>")

print("</html>")

Below is the HTML code for executing the dropdownbox . py.

dropdownbox.html saved inside the folder in htdocs

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

<select name="sex">

<option value="Male" selected > Male </option>

<option value="Female"> Female </option> <br/>

<input type="submit" value="Submit" />

</form>

Note: Ensure both files in same folder inside the htdocs.

21
Output

23. CHECK BOXES

Checkboxes are used when more than one option is required to be selected. The selected
Checkboxes will be tick marked. Below is checkbox.py script to handle input given by web
browser for Checkbox. This code contains 3 Checkboxes.

checkbox.py saved inside the folder in htdocs

#!C:\Users\JOSE\AppData\Local\Programs\Python\Python38\python.exe

#import modules for CGI handling

import cgi, cgitb

# create instance of fieldstorage

form=cgi.FieldStorage()

#get data from fields

if form.getvalue('ECG'):

ECG_flag="ON"

else:

ECG_flag="OFF"

if form.getvalue('XRAY'):

XRAY_flag="ON"

else:

XRAY_flag="OFF"

if form.getvalue('SCAN'):

22
SCAN_flag="ON"

else:

SCAN_flag="OFF"

print("Content-type:text/html")

print()

print("<html>")

print("<head>")

print("<title> CheckBox CGI Program </title>")

print("</head>")

print("<body>")

print("<h2> CheckBox ECG is %s </h2>" %ECG_flag)

print("<h2> CheckBox XRAY is %s </h2>" %XRAY_flag)

print("<h2> CheckBox SCAN is %s </h2>" %SCAN_flag)

print("</body>")

print("</html>")

Below is the HTML code for executing the checkbox.py.

checkbox.html saved inside the folder in htdocs

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

<input type="checkbox" name="ECG" value="on"> ECG<br/>

<input type="checkbox" name="XRAY" value="on"> XRAY<br/>

<input type="checkbox" name="SCAN" value="on"> SCAN<br/>

<input type="submit" value="Select" />

</form>

Note: Ensure both files in same folder inside the htdocs.

23
Output

24. TEXT AREA

The Text Area defines a multi-line text input control. A text area can hold an unlimited
number of characters, and the text renders in a fixed-width font (usually Courier). The size of
a text area can be specified by the cols and rows attributes. Below is textarea.py script to
handle input given by Web browser for text area.

textarea.py saved inside the folder in htdocs

#!C:\Users\JOSE\AppData\Local\Programs\Python\Python38\python.exe

#import modules for CGI handling

import cgi, cgitb

# create instance of fieldstorage

form=cgi.FieldStorage()

#get data from fields

if form.getvalue('textcontent'):

content=form.getvalue('textcontent')

else:

24
content=" Not entered"

print("Content-type:text/html")

print()

print("<html>")

print("<head>")

print("<title> Textarea CGI Program </title>")

print("</head>")

print("<body>")

print("<h2> The entered content is %s </h2>" %content)

print("</body>")

print("</html>")

textarea.html saved inside the folder in htdocs

<form action="textarea.py" method="post" target="_blank">

<textarea name="textcontent" cols="40" rows="4">

Type your text here...

</textarea>

<input type="submit" value="Submit" />

</form>

Output

25
25. COOKIES

An HTTP cookie is a small piece of data sent from a website and stored on the user's
computer by the user's web browser while the user is browsing. Cookies were designed to be
a reliable mechanism for websites to remember stateful information (such as items added in
the shopping cart in an online store) or to record the user's browsing activity (including
clicking particular buttons, logging in, or recording which pages were visited in the past).
They can also be used to remember arbitrary pieces of information that the user previously
entered into form fields such as names, addresses, passwords, and credit card numbers.

Cookie Attributes

In addition to a name and value, cookies can also have one or more attributes. Browsers do
not include cookie attributes in requests to the server. They only send the cookie's name and
value. Cookie attributes are used by browsers to determine when to delete a cookie, block a
cookie or whether to send a cookie to the server.

Name=Value: Cookies are set and retrieved in the form of key and value pairs.

Domain: The domain name of our site.

Path: The path to the directory or web page that sets the cookie. This may be blank if we
want to retrieve the cookie from any directory or page.

Expires: The date on which the cookie will expires. If this is blank, the cookie will expire
when the visitor quits the browser.

Secure: If this field contains the word "secure", then the cookie may only be retrieved with a
secure server. If this field is blank, no such restriction exists.

HttpOnly: The HttpOnly attribute directs browsers not to expose cookies through channels
other than HTTP (and HTTPS) requests. This means that the cookie cannot be accessed via
client-side scripting languages.

26
Setting Up Cookies

Cookies are set using the Set-Cookie HTTP header, sent in an HTTP response from the web
server. This header instructs the web browser to store the cookie and send it back in future
requests to the server. These cookies are sent before to Content-type field. It is optional to set
cookies attributes like Expires, Domain, Path, Secure and HttpOnly. Assuming you want to
set UserID and Password as cookies. Setting the cookies is done as follows.

Example Program

#!C:\Users\JOSE\AppData\Local\Programs\Python\Python38\python.exe

from http import cookies

import os

# setting cookie

cook=cookies.SimpleCookie()

cook["UserID"]="MARY"

cook["UserID"]["expires"]=60*60*24

print("Content-type:text/html")

print()

#print(cook)

print("<html>")

print("<head>")

print("<title> First Cookie Program </title>")

print("</head>")

print("<body>")

print("<h2> Welcome to cookie programming </h2>")

print("</body>")

print("</html>")

27
Retrieving Cookies

Cookies are stored in CGI environment variable HTTP_COOKIE and they will have the form

keyl=valuel ; key2=value2 ; key3 =value3...

Example Program

#!C:\Users\JOSE\AppData\Local\Programs\Python\Python38\python.exe

from http import cookies

import os

# setting cookie

cook=cookies.SimpleCookie()

cook["UserID"]="MARY"

cook["UserID"]["expires"]=60*60*24

#Deleting cookie

#cook["UserID"]["expires"]="Thu, 01, Jan 1970 00:00:00 GMT"

print("Content-type:text/html")

print()

print(cook)

print("<html>")

print("<head>")

print("<title> First Cookie Program </title>")

print("</head>")

print("<body>")

28
print("<h2> Welcome to cookie programming </h2>")

print(cook["UserID"].value) # read cookie value

print("</body>")

print("</html>")

26. UPLOADING FILE

To upload a file, the HTML form must have the enctype attribute set to multipart/form-data.
The input tag with the file type creates a "Browse" button. Following shows the python script
to handle file upload.
Example program

Save the file as test.html inside the folder created in htdocs

<html><body>

<form enctype="multipart/form-data" action="/cgi-bin/testfile.py" method="post">

<p>File: <input type="file" name="filename"></p>

<p><input type="submit" value="Upload"></p>

</form>

</body>

</html>

Save testfile.py file inside C:\xampp\cgi-bin that the folder inside xampp.

#!C:\Users\JOSE\AppData\Local\Programs\Python\Python38\python.exe

import cgi, os,sys

import cgitb; cgitb.enable()

29
# A nested FieldStorage instance holds the file

form = cgi.FieldStorage()

sys.path.insert(0,os.getcwd())

message=None

fileitem = form['filename']

# Test if the file is uploaded

if fileitem.filename:

# strip leading path from file name to avoid directory traversal attacks

fn = os.path.basename(fileitem.filename)

open('C:/xampp/htdocs/Mary' + fn, 'wb').write(fileitem.file.read())

message = 'The file "' + fn + '" was uploaded successfully'

else:

message = 'No file was uploaded'

print( """\

Content-Type: text/html\n

<html><body>

<p>%s</p>

</body></html>

""" % (message,))

OUTPUT

All the files will be uploaded to 'C:/xampp/htdocs/Mary' given inside the testfile.py code
to see the output.

30

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy