Run Python script as CGI program with Apache2 in Linux / Wamp in Windows

If you’ve Apache & Python installed, you can execute your python scripts as CGI programs, which your visitors can access if you host the scripts in a server. You can write your scripts in python (file-name will end with .py) or in perl (extention .pl) or anything else which is compatible.

Step 1 – Write a “Hello, World! ” script in Python

In a text editor, type following code. Give the file name “first.py

#!/usr/bin/env python
print "Content-type: text/html\n"

print "Hello, world!"

The first line is important – it tells where in our computer Python is available. If you’re using windows, use appropriate location, for example, change the first line to something like:

#!C:/Python27/python.exe

Step 2 – Put the script in a suitable directory

Important: If you are in Linux, make your file executable! Type:

chmod +x /path/to/your/first.py

Pretty simple!

  1. Let’s rename the file to first.py and make it executable, if we’re in Linux.
  2. Put it in a directory named “cgi-bin” under our document root. Then, the file may be accessed in the web-browser by simply typing: http://localhost/cgi-bin/first.py

Step 3 – Configure Apache2

Next step is to configure Apache so that it treats our file as a CGI program. Go to the directory where your Apache configuration file exists. In Linux, it resides under /etc/apache2/ and the configuration file is httpd.conf

NOTE: If virtual hosts are enabled (normally the are enabled), changing the httpd.conf will have no effect. You may need to edit particular configuration file for the site which is enabled. Go to the sites-enabled  directory and open the file which is currently enabled (If you have only the file “default” in your /etc/apache2/sites-enabled directory, you should open this file with your text editor)

NOTE: If you are in windows, and using Wamp, you can simply open the httpd.conf file and make following changes.

Edit the configuration file:

Search for the line: ScriptAlias /cgi-bin/ /whatever-path/ – when you find it, comment out the line: that is add a # in front of the line:

#ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/

Then,  paste following lines of code:

<Directory "/location/to/your/cgi-bin/">
AddHandler cgi-script .cgi .py
AllowOverride All
Options +Indexes FollowSymLinks +ExecCGI
Order allow,deny
Allow from all
</Directory>

If your first.py is in /var/www/cgi-bin/ folder, then replace the first line by <Directory “/var/www/cgi-bin”>

You’re done! Now restart Apache to activate all changes.

If you’re in Linux, open a terminal and enter sudo /etc/init.d/apache2 reload to restart Apache. If you’re using Wamp in Windows, you can restart Apache clicking appropriate icons!

 

Test…

 

Fire up your web browser, type http://localhost/cgi-bin/first.py and hit Enter…

 

If you find only the text:

Hello, world!

in the page, then congratulations!

If you find any other text than Hello, world!, something went wrong. Check for your mistakes. Ensure that “cgi_module” Apache module is enabled.

 

You may find this link helpful.

Advertisements

Python MySQLdb equivalent for PHP’s mysql_insert_id()

What you’re looking for is lastrowid property of a cursor object.

Code:

import MySQLdb # MySQLdb module must be installed on the system
connection = MySQLdb.connect(...) # Details skipped
cursor = connection.cursor()
query = "INSERT INTO ... " # put query here
cursor.execute(query)
print cursor.lastrowid # BINGO! This will print the id (auto-increment column) of the last inserted row
# Other codes here

Thanks to this article on the Internet

C style For loop in Python

A for loop in C/C++/PHP/Java Or many well-known programming language will appear as:

int loopStartVariable = 0;
int loopEndVariable = 5;
for(i=loopStartVariable; i < loopEndVariable; i++){
	// do something with i
}

Python has no C-style for loop, which is has is for in loop like foreach loop available in PHP.

To achive the same goal as the code snippet written in C above, we may write following code in python:

loopStartVariable = 0;
loopEndVariable = 5;
for i in range(loopStartVariable, loopEndVariable):
	# Do something with i
print "loop ends here"

Python Tutorial: Dictionaries (Key-value pair Maps) Basics

Dictionary in Python is a data-structure also known as map. Chances are you’re already familiar with them, if using Associative Arrays in PHP or Hashtables in C++ or Java. You may imagine a dictionary as an array, where instead of numerical indexes (the first element of array is indexed as 0, the second element is indexed by 1 and so on), you use string indexes. Each element of a map is accessed (or, indexed) by an unique “key”; so they are also known as key-value pairs. Dictionaries are not sequences, so the order in which elements are added to the dictionary doesn’t matter.

Example

Suppose, we want a data-structure to store information about a cooking recipe. For the recipe, we want to store which food (dish) we’re cooking, how many quantities it serve, and the color of the food being  prepared (don’t ask me why).

You can create a map using this syntax: variable_name = {key:value}

In the following examples, any text after “>>>” is actual code that you use in your Python scripts. You can also type this code in Python command line interpreter. Any line not beginning with “>>>” indicates an output of the previous code.

Code:
>>> D = {'food': 'pudding', 'quantity': 4, 'color': 'pink'}

>>> D['food'] # Fetch value of key 'food'
'pudding'

>>> D['quantity'] += 1 # Add 1 to 'quantity' value

>>> D
{'food': 'pudding', 'color': 'pink', 'quantity': 5}

Alternately, you can create an empty map, and insert key-value pairs later. Unlike Lists (arrays in Python), you can perform out-of-bound assignments:

Code:
>>> D = {}

>>> D['name'] = 'Bob' # Insert element on-the-fly

>>> D['job'] = 'dev'

>>> D['age'] = 4

>>> D
{'age': 4, 'job': 'dev', 'name': 'Bob'}

>>> print D['name']
Bob

Nesting

Like lists, nesting is also possible in maps. Consider the following code pattern:

Code:
>>> rec = {'name': {'first': 'Bob', 'last': 'Smith'},
                  'job': ['dev', 'mgr'],
                  'age': 40.5}

>>> rec['name'] # 'Name' is a nested dictionary
{'last': 'Smith', 'first': 'Bob'}

>>> rec['name']['last'] # Index the nested dictionary
'Smith'

>>> rec['job'] # 'Job' is a nested list
['dev', 'mgr']

>>> rec['job'][-1] # Index the nested list
'mgr'

>>> rec['job'].append('janitor') # Expand Bob's job description in-place

>>> rec
{'age': 40.5, 'job': ['dev', 'mgr', 'janitor'], 'name': {'last': 'Smith', 'first':
'Bob'}}

Free Java Game Code: HangMan Code by Java!

I’ve coded a simple Game by Java – A HangMan Game! To make it interesting, The game is called HangCoder which means, it is played by a programmer! Don’t worry, it only means you will be given words related to programming to guess.

The source code is open and allowed to modify. It is helpful as a quick demonstration of java Swing and AWT components like textboxex, buttons, images and other stuffs. Study the code, modify as you need and make your own Java HangMan!

Download Source From here.

Images: Can be obtained from here (no need to download if you get the zip file above)

Difference between ./ and / (relative path and Absolute path)

In web or desktop programming/command-prompt use, we often come through such situations where we have to use relative/absolute paths. Is there are any differences between the notation “./” and “/” ?

./

Yes, there are! When you use “./” we mean an relative path. Suppose, you are in the location http://www.somedomain.com/some_directory/index.html

Now, if you want to insert an Image file which is located at this directory “some_directory”, you can write following code in your index.html page:

<img src = "./myimage.jpg">

If you want to use an image from a directory “another_dir” on level up, you should use “../”

<img src = "../another_dir/another_image.jpg">

Both some_dir and another_dir are located under the home of your domain (www.somedomain.com).

/

Now, let’s talk about using “/”

“/” means beginning from the Root level of your file system. Suppose, in Linux, you want to Change your current working directory to the directory “etc”. Since “etc” is placed just in the Root directory of your file system (see the image below), you should type something like this in your command-prompt:

cd /etc

If you tried with the command “cd ./etc”, it wouldn’t work! Why? Because “./” means beginning from the Current Working directory. Normally, when you use a command-prompt it selects the user’s Home folder as current working directory. So if you want to go to a directory based on root level, you should use “/” instead of “./”

Image: Unix/Linux File System. See, the folder “etc” stays just below the “root” or “/”

Python Basics: Indent

Previous Article: Beginning Python Prgramming! How to Download, install, compile & run program in Python

In this post I’ll point out some details about the Python language. Important concepts to be clarified.

Python maintains indention strictly:

In python, you should maintain indention strictly! This is necessary to tell python which portion of code is under a block. For example, consider the loop segment below:

 

As you can see, there is no Curly-braces to identify where a loop starts and where ends! Thus, you must maintain indention strictly.

 

 

This entry will be updated eventually!