Bootstrap Input Groups

Bootstrap Input Groups

This chapter explains about one more feature Bootstrap supports, the Input Groups. Input groups are extended Form Controls. Using input groups you can easily prepend and append text or buttons to text-based inputs.

By adding prepended and appended content to an input field, you can add common elements to the user’s input. For example, you can add the dollar symbol, the @ for a Twitter username, or anything else that might be common for your application interface.

To prepend or append elements to a .form-control:

Wrap it in a <div> with class .input-group

As a next step, within that same <div> , place your extra content inside a <span> with class.input-group-addon.

Now place this <span> either before or after the <input> element.

 

For cross browser compatibility, avoid using <select> elements here as they cannot be fully styled in WebKit browsers. Also do not apply input group classes directly to form groups. An input group is an isolated component.

Basic Input Group

Following examples demonstrates basic input group:

<div style="padding: 100px 100px10px;">

   <form class="bs-example bs-example-form" role="form">

      <div class="input-group">

         <span class="input-group-addon">@</span>

         <input type="text" class="form-control" placeholder="twitterhandle">

      </div>

      <br>

 

      <div class="input-group">

         <input type="text" class="form-control">

         <span class="input-group-addon">.00</span>

      </div>

      <br>

      <div class="input-group">

         <span class="input-group-addon">$</span>

         <input type="text" class="form-control">

         <span class="input-group-addon">.00</span>

      </div>

   </form>

</div>

 

Input Group Sizing

You can change the size of the input groups, by adding the relative form sizing classes like.input-group-lg, input-group-sm, input-group-xs to the .input-group itself. The contents within will automatically resize.

Following examples demonstrates this:

<div style="padding: 100px 100px10px;">

   <form class="bs-example bs-example-form" role="form">

      <div class="input-group input-group-lg">

         <span class="input-group-addon">@</span>

         <input type="text" class="form-control" placeholder="Twitterhandle">

      </div><br>

 

      <div class="input-group">

         <span class="input-group-addon">@</span>

         <input type="text" class="form-control" placeholder="Twitterhandle">

      </div><br>

 

      <div class="input-group input-group-sm">

         <span class="input-group-addon">@</span>

         <input type="text" class="form-control" placeholder="Twitterhandle">

      </div>

   </form>

</div>

Checkboxes and radio addons

You can preappend or append radio buttons and checkboxes instead of text as demonstrated in the following example:

<div style="padding: 100px 100px10px;">

   <form class="bs-example bs-example-form" role="form">

      <div class="row">

         <div class="col-lg-6">

            <div class="input-group">

               <span class="input-group-addon">

                  <input type="checkbox">

               </span>

               <input type="text" class="form-control">

            </div><!-- /input-group -->

         </div><!-- /.col-lg-6 --><br>

         <div class="col-lg-6">

            <div class="input-group">

               <span class="input-group-addon">

                  <input type="radio">

               </span>

               <input type="text" class="form-control">

            </div><!-- /input-group -->

         </div><!-- /.col-lg-6 -->

      </div><!-- /.row -->

   </form>

</div>

 

Button addons

You can even preappend or append buttons in input groups. Instead of .input-group-addonclass, you'll need to use class .input-group-btnto wrap the buttons. This is required due to default browser styles that cannot be overridden. Following examples demonstrates this:

<div style="padding: 100px 100px10px;">

   <form class="bs-example bs-example-form" role="form">

      <div class="row">

         <div class="col-lg-6">

            <div class="input-group">

               <span class="input-group-btn">

                  <button class="btnbtn-default" type="button">

                     Go!

                  </button>

               </span>

               <input type="text" class="form-control">

            </div><!-- /input-group -->

         </div><!-- /.col-lg-6 --><br>

         <div class="col-lg-6">

            <div class="input-group">

               <input type="text" class="form-control">

               <span class="input-group-btn">

                  <button class="btnbtn-default" type="button">

                     Go!

                  </button>

               </span>

            </div><!-- /input-group -->

         </div><!-- /.col-lg-6 -->

      </div><!-- /.row -->

   </form>

</div>

Buttons with dropdowns

Adding button with dropdown menus in input groups can be done by simply wrapping the button and dropdown menu in a .input-group-btn class as demonstrated in the following example:

<div style="padding: 100px 100px10px;">

   <form class="bs-example bs-example-form" role="form">

      <div class="row">

         <div class="col-lg-6">

            <div class="input-group">

               <div class="input-group-btn">

                  <button type="button" class="btn btn-default

                     dropdown-toggle" data-toggle="dropdown">

                     DropdownMenu

                     <span class="caret"></span>

                  </button>

                  <ul class="dropdown-menu">

                     <li><ahref="#">Action</a></li>

                     <li><ahref="#">Another action</a></li>

                     <li><ahref="#">Something else here</a></li>

                     <li class="divider"></li>

                     <li><ahref="#">Separated link</a></li>

                  </ul>

               </div><!-- /btn-group -->

               <input type="text" class="form-control">

            </div><!-- /input-group -->

         </div><!-- /.col-lg-6 --><br>

         <div class="col-lg-6">

            <div class="input-group">

               <input type="text" class="form-control">

               <div class="input-group-btn">

                  <button type="button" class="btn btn-default

                     dropdown-toggle" data-toggle="dropdown">

                     DropdownMenu

                     <span class="caret"></span>

                  </button>

                  <ul class="dropdown-menu pull-right">

                     <li><ahref="#">Action</a></li>

                     <li><ahref="#">Another action</a></li>

                     <li><ahref="#">Something else here</a></li>

                     <li class="divider"></li>

                     <li><ahref="#">Separated link</a></li>

                  </ul>

               </div><!-- /btn-group -->

            </div><!-- /input-group -->

         </div><!-- /.col-lg-6 -->

      </div><!-- /.row -->

   </form>

</div>

Segmented buttons

To segment button dropdowns in input groups, use the same general style as the dropdown button but add a primary action along with the dropdown as can be seen in the following example:

<div style="padding: 100px 100px10px;">

   <form class="bs-example bs-example-form" role="form">

      <div class="row">

         <div class="col-lg-6">

            <div class="input-group">

               <div class="input-group-btn">

                  <button type="button" class="btn btn-default"

                    tabindex="-1">Dropdwon Menu

                  </button>

                  <button type="button" class="btn btn-default

                     dropdown-toggle" data-toggle="dropdown" tabindex="-1">

                     <span class="caret"></span>

                     <span class="sr-only">Toggle Dropdown</span>

                  </button>

                  <ul class="dropdown-menu">

                     <li><ahref="#">Action</a></li>

                     <li><ahref="#">Another action</a></li>

                     <li><ahref="#">Something else here</a></li>

                     <li class="divider"></li>

                     <li><ahref="#">Separated link</a></li>

                  </ul>

               </div><!-- /btn-group -->

               <input type="text" class="form-control">

            </div><!-- /input-group -->

         </div><!-- /.col-lg-6 --><br>

         <div class="col-lg-6">

            <div class="input-group">

               <input type="text" class="form-control">

               <div class="input-group-btn">

                  <button type="button" class="btn btn-default"

                    tabindex="-1">Dropdwon Menu

                  </button>

                  <button type="button" class="btn btn-default

                     dropdown-toggle" data-toggle="dropdown" tabindex="-1">

                     <span class="caret"></span>

                     <span class="sr-only">Toggle Dropdown</span>

                  </button>

                  <ul class="dropdown-menu pull-right">

                     <li><ahref="#">Action</a></li>

                     <li><ahref="#">Another action</a></li>

                     <li><ahref="#">Something else here</a></li>

                     <li class="divider"></li>

                     <li><ahref="#">Separated link</a></li>

                  </ul>

               </div><!-- /btn-group -->

            </div><!-- /input-group -->

         </div><!-- /.col-lg-6 -->

      </div><!-- /.row -->

   </form>

</div>

 

Python Dictionary

Python Dictionary

A dictionary is mutable and is another container type that can store any number of Python objects, including other container types. Dictionaries consist of pairs (called items) of keys and their corresponding values.

Python dictionaries are also known as associative arrays or hash tables. The general syntax of a dictionary is as follows:

dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

You can create dictionary in the following way as well:

dict1 = { 'abc': 456 };

dict2 = { 'abc': 123, 98.6: 37 };

Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}.

Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

Accessing Values in Dictionary:

To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value. Following is a simple example:

#!/usr/bin/python

 

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

 

print "dict['Name']: ", dict['Name'];

print "dict['Age']: ", dict['Age'];

When the above code is executed, it produces the following result:

dict['Name']:  Zara

dict['Age']:  7

If we attempt to access a data item with a key, which is not part of the dictionary, we get an error as follows:

#!/usr/bin/python

 

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

 

print "dict['Alice']: ",dict['Alice'];

When the above code is executed, it produces the following result:

dict['Zara']:

Traceback (most recent call last):

  File "test.py", line 4, in <module>

    print "dict['Alice']: ",dict['Alice'];

KeyError: 'Alice'

Updating Dictionary:

You can update a dictionary by adding a new entry or item (i.e., a key-value pair), modifying an existing entry, or deleting an existing entry as shown below in the simple example:

#!/usr/bin/python

 

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

 

dict['Age'] = 8; # update existing entry

dict['School'] = "DPS School"; # Add new entry

 

 

print "dict['Age']: ", dict['Age'];

print "dict['School']: ",dict['School'];

When the above code is executed, it produces the following result:

dict['Age']:  8

dict['School']:  DPS School

Delete Dictionary Elements:

You can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation.

To explicitly remove an entire dictionary, just use the del statement. Following is a simple example:

#!/usr/bin/python

 

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

 

del dict['Name']; # remove entry with key 'Name'

dict.clear();     # remove all entries in dict

del dict ;        # delete entire dictionary

 

print "dict['Age']: ", dict['Age'];

print "dict['School']: ",dict['School'];

This will produce the following result. Note an exception raised, this is because after del dictdictionary does not exist any more:

dict['Age']:

Traceback (most recent call last):

  File "test.py", line 8, in <module>

    print "dict['Age']: ",dict['Age'];

TypeError: 'type' object isunsubscriptable

Note: del() method is discussed in subsequent section.

Properties of Dictionary Keys:

Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-defined objects. However, same is not true for the keys.

There are two important points to remember about dictionary keys:

(a) More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins. Following is a simple example:

#!/usr/bin/python

 

dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'};

 

print "dict['Name']: ", dict['Name'];

When the above code is executed, it produces the following result:

dict['Name']:  Manni

(b) Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed. Following is a simple example:

#!/usr/bin/python

 

dict = {['Name']: 'Zara', 'Age': 7};

 

print "dict['Name']: ", dict['Name'];

When the above code is executed, it produces the following result:

Traceback (most recent call last):

  File "test.py", line 3, in <module>

    dict = {['Name']: 'Zara', 'Age': 7};

TypeError: list objects are unhashable

Built-in Dictionary Functions & Methods:

Python includes the following dictionary functions:

SN

Function with Description

1

cmp(dict1, dict2)
Compares elements of both dict.

2

len(dict)
Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.

3

str(dict)
Produces a printable string representation of a dictionary

4

type(variable)
Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type.

Python includes following dictionary methods

SN

Methods with Description

1

dict.clear()
Removes all elements of dictionary dict

2

dict.copy()
Returns a shallow copy of dictionary dict

3

dict.fromkeys()
Create a new dictionary with keys from seqand values set to value.

4

dict.get(key, default=None)
For key key, returns value or default if key not in dictionary

5

dict.has_key(key)
Returns true if key in dictionary dictfalseotherwise

6

dict.items()
Returns a list of dict's (key, value) tuple pairs

7

dict.keys()
Returns list of dictionary dict's keys

8

dict.setdefault(key, default=None)
Similar to get(), but will setdict[key]=default if key is not already indict

9

dict.update(dict2)
Adds dictionary dict2's key-values pairs todict

10

dict.values()
Returns list of dictionary dict's values

 

Python Decision Making

Python Decision Making

Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

Following is the general form of a typical decision making structure found in most of the programming languages:

Python programming language assumes anynon-zero and non-null values as true, and if it is either zero or null, then it is assumed as falsevalue.

Python programming language provides following types of decision making statements. Click the following links to check their detail.

Statement

Description

if statements

An if statement consists of aboolean expression followed by one or more statements.

if...else statements

An if statement can be followed by an optional else statement, which executes when the boolean expression is false.

nested if statements

You can use one if or else ifstatement inside another if orelse if statement(s).

 

Single Statement Suites:

If the suite of an if clause consists only of a single line, it may go on the same line as the header statement.

Here is an example of a one-line if clause:

#!/usr/bin/python

 

var = 100

 

if ( var  == 100 ) : print "Value of expression is 100"

 

print "Good bye!"

When the above code is executed, it produces the following result:

Value of expression is 100

Good bye!

 

Python Numbers

Python Numbers

Number data types store numeric values. They are immutable data types, which means that changing the value of a number data type results in a newly allocated object.

Number objects are created when you assign a value to them. For example:

var1 = 1

var2 = 10

You can also delete the reference to a number object by using the del statement. The syntax of the del statement is:

del var1[,var2[,var3[....,varN]]]]

You can delete a single object or multiple objects by using the del statement. For example:

del var

del var_a, var_b

Python supports four different numerical types:

int (signed integers): often called just integers or ints, are positive or negative whole numbers with no decimal point.

long (long integers ): or longs, are integers of unlimited size, written like integers and followed by an uppercase or lowercase L.

float (floating point real values) : or floats, represent real numbers and are written with a decimal point dividing the integer and fractional parts. Floats may also be in scientific notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x 102 = 250).

complex (complex numbers) : are of the form a + bJ, where a and b are floats and J (or j) represents the square root of -1 (which is an imaginary number). a is the real part of the number, and b is the imaginary part. Complex numbers are not used much in Python programming.

Examples:

Here are some examples of numbers:

int

long

float

complex

10

51924361L

0.0

3.14j

100

-0x19323L

15.20

45.j

-786

0122L

-21.9

9.322e-36j

080

0xDEFABCECBDAECBFBAEL

32.3+e18

.876j

-0490

535633629843L

-90.

-.6545+0J

-0x260

-052318172735L

-32.54e100

3e+26J

0x69

-4721885298529L

70.2-E12

4.53e-7j

Python allows you to use a lowercase L with long, but it is recommended that you use only an uppercase L to avoid confusion with the number 1. Python displays long integers with an uppercase L.

A complex number consists of an ordered pair of real floatingpoint numbers denoted by a + bj, where a is the real part and b is the imaginary part of the complex number.

Number Type Conversion:

Python converts numbers internally in an expression containing mixed types to a common type for evaluation. But sometimes, you'll need to coerce a number explicitly from one type to another to satisfy the requirements of an operator or function parameter.

Type int(x)to convert x to a plain integer.

Type long(x) to convert x to a long integer.

Type float(x) to convert x to a floating-point number.

Type complex(x) to convert x to a complex number with real part x and imaginary part zero.

Type complex(x, y) to convert x and y to a complex number with real part x and imaginary part y. x and y are numeric expressions

Mathematical Functions:

Python includes following functions that perform mathematical calculations.

Function

Returns ( description )

abs(x)

The absolute value of x: the (positive) distance between x and zero.

ceil(x)

The ceiling of x: the smallest integer not less than x

cmp(x, y)

-1 if x < y, 0 if x == y, or 1 if x > y

exp(x)

The exponential of x: ex

fabs(x)

The absolute value of x.

floor(x)

The floor of x: the largest integer not greater than x

log(x)

The natural logarithm of x, for x> 0

log10(x)

The base-10 logarithm of x for x> 0 .

max(x1, x2,...)

The largest of its arguments: the value closest to positive infinity

min(x1, x2,...)

The smallest of its arguments: the value closest to negative infinity

modf(x)

The fractional and integer parts of x in a two-item tuple. Both parts have the same sign as x. The integer part is returned as a float.

pow(x, y)

The value of x**y.

round(x [,n])

x rounded to n digits from the decimal point. Python rounds away from zero as a tie-breaker:round(0.5) is 1.0 and round(-0.5) is -1.0.

sqrt(x)

The square root of x for x > 0

Random Number Functions:

Random numbers are used for games, simulations, testing, security, and privacy applications. Python includes following functions that are commonly used.

Function

Description

choice(seq)

A random item from a list, tuple, or string.

randrange([start,] stop [,step])

A randomly selected element from range(start, stop, step)

random()

A random float r, such that 0 is less than or equal to r and r is less than 1

seed([x])

Sets the integer starting value used in generating random numbers. Call this function before calling any other random module function. Returns None.

shuffle(lst)

Randomizes the items of a list in place. Returns None.

uniform(x, y)

A random float r, such that x is less than or equal to r and r is less than y

Trigonometric Functions:

Python includes following functions that perform trigonometric calculations.

Function

Description

acos(x)

Return the arc cosine of x, in radians.

asin(x)

Return the arc sine of x, in radians.

atan(x)

Return the arc tangent of x, in radians.

atan2(y, x)

Return atan(y / x), in radians.

cos(x)

Return the cosine of x radians.

hypot(x, y)

Return the Euclidean norm,sqrt(x*x + y*y).

sin(x)

Return the sine of x radians.

tan(x)

Return the tangent of x radians.

degrees(x)

Converts angle x from radians to degrees.

radians(x)

Converts angle x from degrees to radians.

Mathematical Constants:

The module also defines two mathematical constants:

Constants

Description

pi

The mathematical constant pi.

e

The mathematical constant e.

 

Python MySQL Database Access

Python MySQL Database Access

The Python standard for database interfaces is the Python DB-API. Most Python database interfaces adhere to this standard.

You can choose the right database for your application. Python Database API supports a wide range of database servers:

GadFly

mSQL

MySQL

PostgreSQL

Microsoft SQL Server 2000

Informix

Interbase

Oracle

Sybase

Here is the list of available Python database interfaces: Python Database Interfaces and APIs.You must download a separate DB API module for each database you need to access. For example, if you need to access an Oracle database as well as a MySQL database, you must download both the Oracle and the MySQL database modules.

The DB API provides a minimal standard for working with databases using Python structures and syntax wherever possible. This API includes the following:

Importing the API module.

Acquiring a connection with the database.

Issuing SQL statements and stored procedures.

Closing the connection

We would learn all the concepts using MySQL, so let's talk about MySQLdb module only.

What is MySQLdb?

MySQLdb is an interface for connecting to a MySQL database server from Python. It implements the Python Database API v2.0 and is built on top of the MySQL C API.

How do I install the MySQLdb?

Before proceeding, you make sure you have MySQLdb installed on your machine. Just type the following in your Python script and execute it:

#!/usr/bin/python

 

import MySQLdb

If it produces the following result, then it means MySQLdb module is not installed:

Traceback (most recent call last):

  File "test.py", line 3, in <module>

    import MySQLdb

ImportError: No module named MySQLdb

To install MySQLdb module, download it fromMySQLdb Download page and proceed as follows:

$ gunzip MySQL-python-1.2.2.tar.gz

$ tar -xvf MySQL-python-1.2.2.tar

$ cd MySQL-python-1.2.2

$ python setup.py build

$ python setup.py install

Note: Make sure you have root privilege to install above module.

Database Connection:

Before connecting to a MySQL database, make sure of the followings:

You have created a database TESTDB.

You have created a table EMPLOYEE in TESTDB.

This table is having fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.

User ID "testuser" and password "test123" are set to access TESTDB.

Python module MySQLdb is installed properly on your machine.

You have gone through MySQL tutorial to understand MySQL Basics.

Example:

Following is the example of connecting with MySQL database "TESTDB"

#!/usr/bin/python

 

import MySQLdb

 

# Open database connection

db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

 

# prepare a cursor object usingcursor() 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 : %s " % data

 

# disconnect from server

db.close()

While running this script, it is producing the following result in my Linux machine.

Database version : 5.0.45

If a connection is established with the datasource, then a Connection Object is returned and saved into db for further use, otherwise dbis set to None. Next, db object is used to create acursor object, which in turn is used to execute SQL queries. Finally, before coming out, it ensures that database connection is closed and resources are released.

Creating Database Table:

Once a database connection is established, we are ready to create tables or records into the database tables using execute method of the created cursor.

Example:

First, let's create Database table EMPLOYEE:

#!/usr/bin/python

 

import MySQLdb

 

# Open database connection

db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

 

# prepare a cursor object usingcursor() method

cursor = db.cursor()

 

# Drop table if it already exist usingexecute() method.

cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")

 

# Create table as per requirement

sql = """CREATE TABLE EMPLOYEE (

         FIRST_NAME  CHAR(20) NOT NULL,

         LAST_NAME  CHAR(20),

         AGE INT, 

         SEX CHAR(1),

         INCOME FLOAT )"""

 

cursor.execute(sql)

 

# disconnect from server

db.close()

INSERT Operation:

INSERT operation is required when you want to create your records into a database table.

Example:

Following is the example, which executes SQLINSERT statement to create a record into EMPLOYEE table:

#!/usr/bin/python

 

import MySQLdb

 

# Open database connection

db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

 

# prepare a cursor object usingcursor() method

cursor = db.cursor()

 

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

sql = """INSERT INTO EMPLOYEE(FIRST_NAME,

         LAST_NAME, AGE, SEX, INCOME)

         VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""

try:

   # Execute the SQL command

   cursor.execute(sql)

   # Commit your changes in the database

   db.commit()

except:

   # Rollback in case there is any error

   db.rollback()

 

# disconnect from server

db.close()

Above example can be written as follows to create SQL queries dynamically:

#!/usr/bin/python

 

import MySQLdb

 

# Open database connection

db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

 

# prepare a cursor object usingcursor() method

cursor = db.cursor()

 

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

sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \

       LAST_NAME, AGE, SEX, INCOME) \

       VALUES ('%s', '%s', '%d', '%c', '%d' )" % \

       ('Mac', 'Mohan', 20, 'M', 2000)

try:

   # Execute the SQL command

   cursor.execute(sql)

   # Commit your changes in the database

   db.commit()

except:

   # Rollback in case there is any error

   db.rollback()

 

# disconnect from server

db.close()

Example:

Following code segment is another form of execution where you can pass parameters directly:

..................................

user_id = "test123"

password = "password"

 

con.execute('insert into Login values("%s", "%s")' % \

             (user_id, password))

..................................

READ Operation:

READ Operation on any databasse means to fetch some useful information from the database.

Once our database connection is established, we are ready to make a query into this database. We can use either fetchone() method to fetch single record or fetchall() method to fetech multiple values from a database table.

fetchone(): This method 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.

fetchall(): This method fetches all the rows in a result set. If some rows have already been extracted from the result set, the fetchall() method retrieves the remaining rows from the result set.

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

Example:

Following is the procedure to query all the records from EMPLOYEE table having salary more than 1000:

#!/usr/bin/python

 

import MySQLdb

 

# Open database connection

db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

 

# prepare a cursor object usingcursor() method

cursor = db.cursor()

 

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

sql = "SELECT * FROM EMPLOYEE \

       WHERE INCOME > '%d'" % (1000)

try:

   # Execute the SQL command

   cursor.execute(sql)

   # Fetch all the rows in a list of lists.

   results = cursor.fetchall()

   for row in results:

      fname = row[0]

      lname = row[1]

      age = row[2]

      sex = row[3]

      income = row[4]

      # Now print fetched result

      print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \

             (fname, lname, age, sex, income )

except:

   print "Error: unable to fecth data"

 

# disconnect from server

db.close()

This will produce the following result:

fname=Mac, lname=Mohan, age=20, sex=M, income=2000

Update Operation:

UPDATE Operation on any databasse means to update one or more records, which are already available in the database. Following is the procedure to update all the records having SEX as 'M'. Here, we will increase AGE of all the males by one year.

Example:

#!/usr/bin/python

 

import MySQLdb

 

# Open database connection

db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

 

# prepare a cursor object usingcursor() method

cursor = db.cursor()

 

# Prepare SQL query to UPDATE required records

sql = "UPDATE EMPLOYEE SET AGE = AGE + 1

                          WHERE SEX = '%c'" % ('M')

try:

   # Execute the SQL command

   cursor.execute(sql)

   # Commit your changes in the database

   db.commit()

except:

   # Rollback in case there is any error

   db.rollback()

 

# disconnect from server

db.close()

DELETE Operation:

DELETE operation is required when you want to delete some records from your database. Following is the procedure to delete all the records from EMPLOYEE where AGE is more than 20:

Example:

#!/usr/bin/python

 

import MySQLdb

 

# Open database connection

db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

 

# prepare a cursor object usingcursor() method

cursor = db.cursor()

 

# Prepare SQL query to DELETE required records

sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)

try:

   # Execute the SQL command

   cursor.execute(sql)

   # Commit your changes in the database

   db.commit()

except:

   # Rollback in case there is any error

   db.rollback()

 

# disconnect from server

db.close()

Performing Transactions:

Transactions are a mechanism that ensures data consistency. Transactions should have the following four properties:

Atomicity: Either a transaction completes or nothing happens at all.

Consistency: A transaction must start in a consistent state and leave the system in a consistent state.

Isolation: Intermediate results of a transaction are not visible outside the current transaction.

Durability: Once a transaction was committed, the effects are persistent, even after a system failure.

The Python DB API 2.0 provides two methods to either commit or rollback a transaction.

Example:

You already have seen how we have implemented transations. Here is again similar example:

# Prepare SQL query to DELETE required records

sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)

try:

   # Execute the SQL command

   cursor.execute(sql)

   # Commit your changes in the database

   db.commit()

except:

   # Rollback in case there is any error

   db.rollback()

COMMIT Operation:

Commit is the operation, which gives a green signal to database to finalize the changes, and after this operation, no change can be reverted back.

Here is a simple example to call commit method.

 db.commit()

ROLLBACK Operation:

If you are not satisfied with one or more of the changes and you want to revert back those changes completely, then use rollback()method.

Here is a simple example to call rollback()method.

 db.rollback()

Disconnecting Database:

To disconnect Database connection, use close() method.

 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 DB. However, instead of depending on any of DB lower level implementation details, your application would be better off calling commit or rollback explicitly.

Handling Errors:

There are many sources of errors. 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 DB API defines a number of errors that must exist in each database module. The following table lists these exceptions.

Exception

Description

Warning

Used for non-fatal issues. Must subclass StandardError.

Error

Base class for errors. Must subclass StandardError.

InterfaceError

Used for errors in the database module, not the database itself. Must subclass Error.

DatabaseError

Used for errors in the database. Must subclass Error.

DataError

Subclass of DatabaseError that refers to errors in the data.

OperationalError

Subclass of DatabaseError that refers to errors such as the loss of a connection to the database. These errors are generally outside of the control of the Python scripter.

IntegrityError

Subclass of DatabaseError for situations that would damage the relational integrity, such as uniqueness constraints or foreign keys.

InternalError

Subclass of DatabaseError that refers to errors internal to the database module, such as a cursor no longer being active.

ProgrammingError

Subclass of DatabaseError that refers to errors such as a bad table name and other things that can safely be blamed on you.

NotSupportedError

Subclass of DatabaseError that refers to trying to call unsupported functionality.

Your Python scripts should handle these errors, but before using any of the above exceptions, make sure your MySQLdb has support for that exception. You can get more information about them by reading the DB API 2.0 specification.

Python Tuples

Python Tuples

A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The only difference is that tuples can't be changed i.e., tuples are immutable and tuples use parentheses and lists use square brackets.

Creating a tuple is as simple as putting different comma-separated values and optionally you can put these comma-separated values between parentheses also. For example:

tup1 = ('physics', 'chemistry', 1997, 2000);

tup2 = (1, 2, 3, 4, 5 );

tup3 = "a", "b", "c", "d";

The empty tuple is written as two parentheses containing nothing:

tup1 = ();

To write a tuple containing a single value you have to include a comma, even though there is only one value:

tup1 = (50,);

Like string indices, tuple indices start at 0, and tuples can be sliced, concatenated and so on.

Accessing Values in Tuples:

To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index. Following is a simple example:

#!/usr/bin/python

 

tup1 = ('physics', 'chemistry', 1997, 2000);

tup2 = (1, 2, 3, 4, 5, 6, 7 );

 

print "tup1[0]: ", tup1[0]

print "tup2[1:5]: ", tup2[1:5]

When the above code is executed, it produces the following result:

tup1[0]:  physics

tup2[1:5]:  [2, 3, 4, 5]

Updating Tuples:

Tuples are immutable which means you cannot update or change the values of tuple elements. You are able to take portions of existing tuples to create new tuples as the following example demonstrates:

#!/usr/bin/python

 

tup1 = (12, 34.56);

tup2 = ('abc', 'xyz');

 

# Following action is not valid for tuples

# tup1[0] = 100;

 

# So let's create a new tuple as follows

tup3 = tup1 + tup2;

print tup3;

When the above code is executed, it produces the following result:

(12, 34.56, 'abc', 'xyz')

Delete Tuple Elements:

Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded.

To explicitly remove an entire tuple, just use thedel statement. Following is a simple example:

#!/usr/bin/python

 

tup = ('physics', 'chemistry', 1997, 2000);

 

print tup;

del tup;

print "After deleting tup : "

print tup;

This will produce following result. Note an exception raised, this is because after del tuptuple does not exist any more:

('physics', 'chemistry', 1997, 2000)

After deleting tup :

Traceback (most recent call last):

  File "test.py", line 9, in <module>

    print tup;

NameError: name 'tup' is not defined

Basic Tuples Operations:

Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new tuple, not a string.

In fact, tuples respond to all of the general sequence operations we used on strings in the prior chapter :

Python Expression

Results

Description

len((1, 2, 3))

3

Length

(1, 2, 3) + (4, 5, 6)

(1, 2, 3, 4, 5, 6)

Concatenation

('Hi!',) * 4

('Hi!', 'Hi!', 'Hi!', 'Hi!')

Repetition

3 in (1, 2, 3)

True

Membership

for x in (1, 2, 3): print x,

1 2 3

Iteration

Indexing, Slicing, and Matrixes:

Because tuples are sequences, indexing and slicing work the same way for tuples as they do for strings. Assuming following input:

L = ('spam', 'Spam', 'SPAM!')

 

Python Expression

Results

Description

L[2]

'SPAM!'

Offsets start at zero

L[-2]

'Spam'

Negative: count from the right

L[1:]

['Spam', 'SPAM!']

Slicing fetches sections

No Enclosing Delimiters:

Any set of multiple objects, comma-separated, written without identifying symbols, i.e., brackets for lists, parentheses for tuples, etc., default to tuples, as indicated in these short examples:

#!/usr/bin/python

 

print 'abc', -4.24e93, 18+6.6j, 'xyz';

x, y = 1, 2;

print "Value of x , y : ", x,y;

When the above code is executed, it produces the following result:

abc -4.24e+93 (18+6.6j) xyz

Value of x , y : 1 2

Built-in Tuple Functions:

Python includes the following tuple functions:

SN

Function with Description

1

cmp(tuple1, tuple2)
Compares elements of both tuples.

2

len(tuple)
Gives the total length of the tuple.

3

max(tuple)
Returns item from the tuple with max value.

4

min(tuple)
Returns item from the tuple with min value.

5

tuple(seq)
Converts a list into tuple.

 

 

Python CGI Programming

Python CGI Programming

What is CGI?

The Common Gateway Interface, or CGI, is a set of standards that define how information is exchanged between the web server and a custom script.

The CGI specs are currently maintained by the NCSA and NCSA defines CGI is as follows:

The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers.

The current version is CGI/1.1 and CGI/1.2 is under progress.

Web Browsing

To understand the concept of CGI, lets see what happens when we click a hyper link to browse a particular web page or URL.

Your browser contacts the HTTP web server and demands for the URL i.e., filename.

Web Server will parse the URL and will look for the filename in if it finds that file then sends it back to the browser, otherwise sends an error message indicating that you have requested a wrong file.

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

However, 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 your browser to display. This function is called the Common Gateway Interface or CGI and the programs are called CGI scripts. These CGI programs can be a Python Script, PERL Script, Shell Script, C or C++ program, etc.

CGI Architecture Diagram

Web Server Support & Configuration

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 files will have extension as .cgi, but you can keep your files with python extension .py as well.

By default, the Linux server is configured to run only the scripts in the cgi-bin directory in /var/www. If you want to specify any other directory to run your CGI scripts, comment the following lines in the httpd.conf file:

<Directory "/var/www/cgi-bin">

   AllowOverride None

   Options ExecCGI

   Order allow,deny

   Allow from all

</Directory>

 

<Directory "/var/www/cgi-bin">

Options All

</Directory>

Here, I assumed that you have Web Server up and running successfully and you are able to run any other CGI program like Perl or Shell, etc.

First CGI Program

Here is a simple link, which is linked to a CGI script called hello.py. This file is being kept in /var/www/cgi-bin directory and it has following content. Before running your CGI program, make sure you have change mode of file usingchmod 755 hello.py UNIX command to make file executable.

#!/usr/bin/python

 

print "Content-type:text/html\r\n\r\n"

print '<html>'

print '<head>'

print '<title>Hello Word - First CGI Program</title>'

print '</head>'

print '<body>'

print '<h2>Hello Word! This is my first CGI program</h2>'

print '</body>'

print '</html>'

If you click hello.py, then this produces the following output:

Hello Word! This is my first CGI program

This hello.py script is a simple Python script, which is writing its output on STDOUT file i.e., screen. There is one important and extra feature available which is first line to be printedContent-type:text/html\r\n\r\n. This line is sent back to the browser and specifiy the content type to be displayed on the browser screen.

Now, you must have understood basic concept of CGI and you can write many complicated CGI programs using Python. This script can interact with any other external system also to exchange information such as RDBMS.

HTTP Header

The line Content-type:text/html\r\n\r\n is part of HTTP header which is sent to the browser to understand the content. All the HTTP header will be in the following form:

HTTP Field Name: Field Content

 

For Example

Content-type: text/html\r\n\r\n

There are few other important HTTP headers, which you will use frequently in your CGI Programming.

Header

Description

Content-type:

A MIME string defining the format of the file being returned. Example is Content-type:text/html

Expires: Date

The date the information becomes invalid. This should be used by the browser to decide when a page needs to be refreshed. A valid date string should be in the format 01 Jan 1998 12:00:00 GMT.

Location: URL

The URL that should be returned instead of the URL requested. You can use this field to redirect a request to any file.

Last-modified: Date

The date of last modification of the resource.

Content-length: N

The length, in bytes, of the data being returned. The browser uses this value to report the estimated download time for a file.

Set-Cookie: String

Set the cookie passed through the string

 

CGI Environment Variables

All the CGI program will have access to the following environment variables. These variables play an important role while writing any CGI program.

Variable Name

Description

CONTENT_TYPE

The data type of the content. Used when the client is sending attached content to the server. For example, file upload, etc.

CONTENT_LENGTH

The length of the query information. It's available only for POST requests.

HTTP_COOKIE

Returns the set cookies in the form of key & value pair.

HTTP_USER_AGENT

The User-Agent request-header field contains information about the user agent originating the request. Its name of the web browser.

PATH_INFO

The path for the CGI script.

QUERY_STRING

The URL-encoded information that is sent with GET method request.

REMOTE_ADDR

The IP address of the remote host making the request. This can be useful for logging or for authentication purpose.

REMOTE_HOST

The fully qualified name of the host making the request. If this information is not available then REMOTE_ADDR can be used to get IR address.

REQUEST_METHOD

The method used to make the request. The most common methods are GET and POST.

SCRIPT_FILENAME

The full path to the CGI script.

SCRIPT_NAME

The name of the CGI script.

SERVER_NAME

The server's hostname or IP Address

SERVER_SOFTWARE

The name and version of the software the server is running.

 

Here is small CGI program to list out all the CGI variables. Click this link to see the result Get Environment

#!/usr/bin/python

 

import os

 

print "Content-type: text/html\r\n\r\n";

print "<font size=+1>Environment</font><\br>";

for param in os.environ.keys():

  print "<b>%20s</b>: %s<\br>" % (param, os.environ[param])

GET and POST Methods

You must have come across many situations when you need to pass some information from your browser to web server and ultimately to your CGI Program. Most frequently, browser uses two methods two pass this information to web server. These methods are GET Method and POST Method.

Passing Information using GET method:

The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character as follows:

http://www.test.com/cgi-bin/hello.py?key1=value1&key2=value2

The GET method is the default method to pass information from browser to web server and it produces a long string that appears in your browser's Location:box. Never use GET method if you have password or other sensitive information to pass to the server. The GET method has size limtation: only 1024 characters can be sent in a request string. The GET method sends information using QUERY_STRING header and will be accessible in your CGI Program through QUERY_STRING environment variable.

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

Simple URL Example : Get Method

Here is a simple URL, which will pass two values to hello_get.py program using GET method.

/cgi-bin/hello_get.py?first_name=ZARA&last_name=ALI

Below is hello_get.py script to handle input given by web browser. We are going to use cgimodule, which makes it very easy to access passed information:

#!/usr/bin/python

 

# Import modules for CGI handling

import cgi, cgitb

 

# Create instance of FieldStorage

form = cgi.FieldStorage()

 

# Get data from fields

first_name = form.getvalue('first_name')

last_name  = form.getvalue('last_name')

 

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 "<h2>Hello %s %s</h2>" % (first_name, last_name)

print "</body>"

print "</html>"

This would generate the following result:

Hello ZARA ALI

Simple FORM Example: GET Method

Here is a simple example which passes two values using HTML FORM and submit button. We are going to use same CGI script hello_get.py to handle this imput.

<form action="/cgi-bin/hello_get.py" method="get">

First Name: <input type="text" name="first_name">  <br />

 

Last Name: <input type="text" name="last_name" />

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

</form>

Here is the actual output of the above form, You enter First and Last Name and then click submit button to see the result.

First Name: 
Last Name: 

Passing Information using POST method:

A generally more reliable method of passing information to a CGI program is the POST method. This packages the information in exactly the same way as GET methods, but instead of sending it as a text string after a ? in the URL it sends it as a separate message. This message comes into the CGI script in the form of the standard input.

Below is same hello_get.py script which handles GET as well as POST method.

#!/usr/bin/python

 

# Import modules for CGI handling

import cgi, cgitb

 

# Create instance of FieldStorage

form = cgi.FieldStorage()

 

# Get data from fields

first_name = form.getvalue('first_name')

last_name  = form.getvalue('last_name')

 

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 "<h2>Hello %s %s</h2>" % (first_name, last_name)

print "</body>"

print "</html>"

Let us take again same example as above which passes two values using HTML FORM and submit button. We are going to use same CGI script hello_get.py to handle this imput.

<form action="/cgi-bin/hello_get.py" method="post">

First Name: <input type="text" name="first_name"><br />

Last Name: <input type="text" name="last_name" />

 

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

</form>

Here is the actual output of the above form. You enter First and Last Name and then click submit button to see the result.

First Name: 
Last Name: 

Passing Checkbox Data to CGI Program

Checkboxes are used when more than one option is required to be selected.

Here is example HTML code for a form with two checkboxes:

<form action="/cgi-bin/checkbox.cgi" method="POST" target="_blank">

<input type="checkbox" name="maths" value="on" /> Maths

<input type="checkbox" name="physics" value="on" /> Physics

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

</form>

The result of this code is the following form:

Maths Physics

Below is checkbox.cgi script to handle input given by web browser for checkbox button.

#!/usr/bin/python

 

# Import modules for CGI handling

import cgi, cgitb

 

# Create instance of FieldStorage

form = cgi.FieldStorage()

 

# Get data from fields

if form.getvalue('maths'):

   math_flag = "ON"

else:

   math_flag = "OFF"

 

if form.getvalue('physics'):

   physics_flag = "ON"

else:

   physics_flag = "OFF"

 

print "Content-type:text/html\r\n\r\n"

print "<html>"

print "<head>"

print "<title>Checkbox - Third CGI Program</title>"

print "</head>"

print "<body>"

print "<h2> CheckBox Maths is : %s</h2>" % math_flag

print "<h2> CheckBox Physics is : %s</h2>" % physics_flag

print "</body>"

print "</html>"

Passing Radio Button Data to CGI Program

Radio Buttons are used when only one option is required to be selected.

Here is example HTML code for a form with two radio buttons:

<form action="/cgi-bin/radiobutton.py" method="post" target="_blank">

<input type="radio" name="subject" value="maths" /> Maths

<input type="radio" name="subject" value="physics" /> Physics

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

</form>

The result of this code is the following form:

Maths Physics

Below is radiobutton.py script to handle input given by web browser for radio button:

#!/usr/bin/python

 

# Import modules for CGI handling

import cgi, cgitb

 

# Create instance of FieldStorage

form = cgi.FieldStorage()

 

# Get data from fields

if form.getvalue('subject'):

   subject = form.getvalue('subject')

else:

   subject = "Not set"

 

print "Content-type:text/html\r\n\r\n"

print "<html>"

print "<head>"

print "<title>Radio - Fourth CGI Program</title>"

print "</head>"

print "<body>"

print "<h2> Selected Subject is %s</h2>" % subject

print "</body>"

print "</html>"

Passing Text Area Data to CGI Program

TEXTAREA element is used when multiline text has to be passed to the CGI Program.

Here is example HTML code for a form with a TEXTAREA box:

<form action="/cgi-bin/textarea.py" method="post" target="_blank">

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

Type your text here...

</textarea>

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

</form>

The result of this code is the following form:

Below is textarea.cgi script to handle input given by web browser:

#!/usr/bin/python

 

# Import modules for CGI handling

import cgi, cgitb

 

# Create instance of FieldStorage

form = cgi.FieldStorage()

 

# Get data from fields

if form.getvalue('textcontent'):

   text_content = form.getvalue('textcontent')

else:

   text_content = "Not entered"

 

print "Content-type:text/html\r\n\r\n"

print "<html>"

print "<head>";

print "<title>Text Area - Fifth CGI Program</title>"

print "</head>"

print "<body>"

print "<h2> Entered Text Content is %s</h2>" % text_content

print "</body>"

Passing Drop Down Box Data to CGI Program

Drop Down Box is used when we have many options available but only one or two will be selected.

Here is example HTML code for a form with one drop down box:

<form action="/cgi-bin/dropdown.py" method="post" target="_blank">

<select name="dropdown">

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

<option value="Physics">Physics</option>

</select>

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

</form>

The result of this code is the following form:

Below is dropdown.py script to handle input given by web browser.

#!/usr/bin/python

 

# Import modules for CGI handling

import cgi, cgitb

 

# Create instance of FieldStorage

form = cgi.FieldStorage()

 

# Get data from fields

if form.getvalue('dropdown'):

   subject = form.getvalue('dropdown')

else:

   subject = "Not entered"

 

print "Content-type:text/html\r\n\r\n"

print "<html>"

print "<head>"

print "<title>Dropdown Box - Sixth CGI Program</title>"

print "</head>"

print "<body>"

print "<h2> Selected Subject is %s</h2>" % subject

print "</body>"

print "</html>"

Using Cookies in CGI

HTTP protocol is a stateless protocol. But for a commercial website, it is required to maintain session information among different pages. For example, one user registration ends after completing many pages. But how to maintain user's session information across all the web pages.

In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics.

How It Works?

Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page on your site, the cookie is available for retrieval. Once retrieved, your server knows/remembers what was stored.

Cookies are a plain text data record of 5 variable-length fields:

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

Domain : The domain name of your site.

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

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.

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

Setting up Cookies

It is very easy to send cookies to browser. These cookies will be sent along with HTTP Header before to Content-type field. Assuming you want to set UserID and Password as cookies. So cookies setting will be done as follows:

#!/usr/bin/python

 

print "Set-Cookie:UserID=XYZ;\r\n"

print "Set-Cookie:Password=XYZ123;\r\n"

print "Set-Cookie:Expires=Tuesday, 31-Dec-2007 23:12:40 GMT";\r\n"

print "Set-Cookie:Domain=www.tutorialspoint.com;\r\n"

print "Set-Cookie:Path=/perl;\n"

print "Content-type:text/html\r\n\r\n"

...........Rest of the HTML Content....

From this example, you must have understood how to set cookies. We use Set-Cookie HTTP header to set cookies.

Here, it is optional to set cookies attributes like Expires, Domain and Path. It is notable that cookies are set before sending magic line"Content-type:text/html\r\n\r\n.

Retrieving Cookies

It is very easy to retrieve all the set cookies. Cookies are stored in CGI environment variable HTTP_COOKIE and they will have following form:

key1=value1;key2=value2;key3=value3....

Here is an example of how to retrieve cookies.

#!/usr/bin/python

 

# Import modules for CGI handling

from os import environ

import cgi, cgitb

 

if environ.has_key('HTTP_COOKIE'):

   for cookie in map(strip, split(environ['HTTP_COOKIE'], ';')):

      (key, value ) = split(cookie, '=');

      if key == "UserID":

         user_id = value

 

      if key == "Password":

         password = value

 

print "User ID  = %s" % user_id

print "Password = %s" % password

This will produce the following result for the cookies set by above script:

User ID = XYZ

Password = XYZ123

File Upload Example:

To upload a file, the HTML form must have the enctype attribute set to multipart/form-data. The input tag with the file type will create a "Browse" button.

<html>

<body>

   <form enctype="multipart/form-data"

                    action="save_file.py" method="post">

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

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

   </form>

</body>

</html>

The result of this code is the following form:

File:

Above example has been disabled intentionally to save people uploading file on our server, but you can try above code with your server.

Here is the script save_file.py to handle file upload:

#!/usr/bin/python

 

import cgi, os

import cgitb; cgitb.enable()

 

form = cgi.FieldStorage()

 

# Get filename here.

fileitem = form['filename']

 

# Test if the file was uploaded

if fileitem.filename:

   # strip leading path from file name to avoid

   # directory traversal attacks

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

   open('/tmp/' + 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,)

If you are running above script on Unix/Linux, then you would have to take care of replacing file separator as follows, otherwise on your windows machine above open() statement should work fine.

fn = os.path.basename(fileitem.filename.replace("\\", "/" ))

How To Raise a "File Download" Dialog Box ?

Sometimes, it is desired that you want to give option where a user will click a link and it will pop up a "File Download" dialogue box to the user instead of displaying actual content. This is very easy and will be achieved through HTTP header. This HTTP header will be different from the header mentioned in previous section.

For example,if you want make a FileName file downloadable from a given link, then its syntax will be as follows:

#!/usr/bin/python

 

# HTTP Header

print "Content-Type:application/octet-stream; name=\"FileName\"\r\n";

print "Content-Disposition:attachment; filename=\"FileName\"\r\n\n";

 

# Actual File Content will go hear.

fo = open("foo.txt", "rb")

 

str = fo.read();

print str

 

# Close opend file

fo.close()

Hope you enjoyed this tutorial. If yes, please send me your feedback at:me@sambhajikarad.info