Monday, December 12, 2011

Mod_Python tutorial

Introduction

Mod_python is an Apache module that embeds the Python interpreter within the server. Mod_python is an Apache HTTP Server module that integrates the Python programming language into the Apache server. It is intended to replace Common Gateway Interface (CGI) as a method of executing Python scripts on a web server. The promised benefits are faster execution speed and maintaining data over multiple sessions.

Benefits of Mod_Pyhton

Ordinary CGI execution starts a new process every time a connection is made to a script on the server. This works well in low to medium traffic sites, but does not scale well when used on a high traffic site. This is exactly what mod_python is designed to do. Since the process is not terminated after the script execution like CGI, persistent data can be stored, such as database connections. This may reduce script execution overhead.

Since mod_python modules are integrated with the web server, they can do almost anything an Apache module written in C can do: implement protocols besides HTTP, filter the request and response, determine a document's content type, etc.

Another advantage to mod_python is that it can talk directly to Apache's core system, and interface as well as actually control the heart of Apache. This is done by handlers that the programmer specifies in the Apache configuration file, and every client request directed at that specific directory will not be processed by Apache, rather by mod_python and a "Main" function that handles all requests.

Install Apache with mod_python
For installation process you can visit following link

http://www.modpython.org/live/current/doc-html/inst-installing.html

I'm using Apache 2 and mod_python 3.1.3. After installation you need to configure Apache to load the mod_python module. This is done in the Apache configuration file which usually is httpd.conf

LoadModule python_module /usr/lib/apache2/modules/mod_python.so

You also need to tell mod_python where your Python application is.

Alias /python /var/www/python

SetHandler python-program
PythonHandler application
# Disable these in production
PythonDebug on
PythonAutoReload on


Write your application

The following code is saved in /var/www/python/application.py. The code demonstrates how to use the mod_python API to manipulate the request and response.
from mod_python import apache, util """ Simple mod_python handler. That demonstrates how to use mod_python's API. """  def handler(request):          # Add HTTP headers to the response     request.headers_out.add("version", "0.1")      # Set content type     request.content_type = "text/plain"         # Send headers to browser     request.send_http_header()      # Get request parameters     parameters = util.FieldStorage(request)          # Send a HTTP redirect     if parameters.get("redirect", None) == "true":         util.redirect(request, location = "http://www.google.com", permanent = False, text = "Resource found")          # Read request parameter named url.     url = parameters.get("url", "parameter not found")          # Read HTTP header from request     connectionHeader = request.headers_in.get('Connection')          # Write Hello world to the browser     request.write("Hello world")      # Send HTTP 200     return apache.OK 
Test your application

You can access your web application at http://localhost/python/application. You should see Hello World in your browser.

Gregory Trubetskoy has written a paper about mod_python. He uses the Publisher and PSP modules which are part of mod_python. This results in more readable code. Which more resemble Servlets and JSPs in Java.

Tuesday, November 22, 2011

Sample example for python

#! python

print "Hello, Python"
a = 10
print a
fruits = ['banana', 'orange', 'apple', 'mango']
for index in range(len(fruits)):
print 'Current fruit :', fruits[index]

print "thanks"

##################################################

for letter in 'Is A Good Boy':
if letter == 'I':
pass
print "block passed"
print 'Current is :', letter

##################################################

var = 10
while var > 0:
print 'Current is value:', var
var -= 1
if var == 5:
break
###################################################

def printme (str):
"this function prints only this line"
print str
return

printme ("hello ji")

##################################################

# Fibonacci series:

a, b = 0, 1
while b < 200:
print b,
a, b = b, a+b

###################################################

# input and operator if

x = int(raw_input("Please enter an integer: "))

if x < 0:
x = 0
print 'Negative changed to zero'
elif x == 0:
print 'Zero'
elif x == 1:
print 'Single'
else:
print 'More'

##################################################

# operator for:

a = ['cat', 'window', 'defenestrate']
for x in a:
print x, len(x)

###################################################

# range function

print range(10)

print range(5, 10)

print range(0, 10, 3)


a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
print i, a[i]

###################################################


for n in range(2, 1000):
for x in range(2, n):
if n % x == 0:
print n, 'equals', x, '*', n/x
break
else:
# loop fell through without finding a factor
print n, 'is a prime number'

####################################################


# Dictionaries are sometimes as ``associative memories'' or ``associative arrays''

tel = {'jack': 4098, 'sape': 4139}
tel['guido'] = 4127
print tel

print tel['jack']

del tel['sape']
tel['irv'] = 4127
print tel

print tel.keys()

x=tel.has_key('guido')
print x

Monday, November 21, 2011

How to Install Python on Windows

Here are simple steps to install and write your first program in python on Windows. It will hardly take 10 mins.

Download Active Pythong

  • Unless you know you have a newer 64-bit machine, play it safe and click on the “x86″ 32-bit version. You’ll also notice newer distributions of Python listed farther down the page. For now, use the version recommended by ActiveState in the blue bars. You can come back later and install a newer distribution once you become a Python convert, but most tutorials for new users are still written for older Python versions, so be conservative for now.
  • When you click on the blue bar, Python should begin downloading.
  • Make a note of where you download this file on your computer.
  • Double-click on the ActivePython file.
  • Up pops the ActiveState box and tells you it’s going to install ActivePython. Click Next.
  • Up pops the Licensing Agreement. Check the Accept box. Click Next.
  • Up pops a dialogue box allowing you to customize the installation. Don’t customize it. Click Next.
  • See the button that says “Install”? Click it.
  • You’re done, and the ActivePython User Guide appears.
  • Now go to START | All Programs | ActiveState ActivePython (version number) (32-bit)
  • The menu will break out into submenus. You want the one that says: “IDLE (Python GUI)” Click on it.
  • Your cursor will be blinking just to the right of a prompt that looks like this: >>>
  • Type the following command there and make sure that “Hello World!” is inside quotation marks:
    >>> print “Hello World!”
  • Press Enter. You should see Hello World! appear in a different-colored font on the line below.
  • If so, you’re done!
  • If you get an error message that says: “SyntaxError: invalid syntax” then you either forgot the quotation marks or you installed Python version 3.0 or greater, which uses a different print command.

Python Print Hello World


Monday, March 8, 2010

NS-2 Installation error solved

While installing NS-2 in ubuntu if you are getting problem like

Usage: host [-v] [-a] [-t querytype] [options] name [server]
Listing: host [-v] [-a] [-t querytype] [options] -l zone [server]
Hostcount: host [-v] [options] -H [-D] [-E] [-G] zone
Check soa: host [-v] [options] -C zone
Addrcheck: host [-v] [options] -A host
Listing options: [-L level] [-S] [-A] [-p] [-P prefserver] [-N skipzone]
Common options: [-d] [-f|-F file] [-I chars] [-i|-n] [-q] [-Q] [-T] [-Z]
Other options: [-c class] [-e] [-m] [-o] [-r] [-R] [-s secs] [-u] [-w]
Special options: [-O srcaddr] [-j minport] [-J maxport]
Extended usage: [-x [name ...]] server [name ...]]



Than you can fix this problem by:

Copy all the files from
/home/username/ns2-allinoneX.XX/bin/

and paste it to /usr/bin/

and then try to run ns
it will work

Sunday, October 25, 2009

NS install

While installing NS you can get few problem, so to fix those problem follow this link....


http://caia.swin.edu.au/cv/kstoeckigt/ns2-install.html

Thursday, September 10, 2009

HOW TO OPEN .chm FILE IN LINUX

Chm file is a Microsoft Compressed HTML Help file in a proprietary format for online help files. Under Linux/FreeBSD or UNIX you can open .chm file using following three different programs which makes it possible to browse native Windows CHM files:

Install chm viewer

Use apt-get or yum command to install chm viewer:
# apt-get install gnochm
OR
# apt-get install kchmviewer

Gnome Desktop User

Use gnochm program as follows
$ gnochm file.chm

KDE Desktop User

Use kchmviewer (very nice and highly recommended) program as follows
$ kchmviewer file.chm

Thursday, August 20, 2009

Default Values in ns2

All the default values in ns2 are located in a file name
"ns-default.tcl"
You can fine this file in directory
"/home/uesrname/ns-allinone-2.xx/ns-2.xx/tcl/lib"

This file actually set up all the default paramters. Each default parameter is stored in the OTcl class template and copied from the class into the instance when the object is created.