Python Examples

You can read about the Python programming language here.  I would recommend using Python 2.6 and not Python 3.1.  All information on this site will refer to Python 2.6, and most information you will find on the web at large will refer to 2.6.

Hello, World!

The hello-world program in Python is rather straightforward:

print 'hello world'

SQL and Python

It is easy to connect to a database with Python using the standard library.  Here is an example of reading from a database using the sqlite3 module:

import sqlite3


conn = sqlite3.connect ('test.db')


# create a cursor to navigate this database
c = conn.cursor ()                    


# execute an SQL statement; results are stored in the cursor
c.execute ('select * from tasks')     

# iterate thru rows of the resulting table
for row in c:                         
    print "task: %s, priority: %i" % (row [0], row [1])

Python HTTP Server

The Python standard library includes an HTTPServer class that is defined in the BaseHTTPServer module.  The HTTPServer class uses a "request handler" object to respond to GET/HEAD/POST/etc requests.  The SimpleHTTPServer module provides a very basic request handler class called SimpleHTTPRequestHandler.  You can start an http server using the SimpleHTTPRequestHandler as follows:

# import the proper modules:
import SimpleHTTPServer
import BaseHTTPServer

# configure httpd parameters
server_addr = ('localhost', 8000)
request_handler = SimpleHTTPServer.SimpleHTTPRequestHandler

# instantiate a server object
httpd = BaseHTTPServer.HTTPServer (server_addr, request_handler)

# start serving pages
httpd.serve_forever ()

Run the script and point your browser at localhost:8000.

Config Parser

To read an INI-like configuration file, you can use the ConfigParser module as follows:
import ConfigParser

config = ConfigParser.RawConfigParser()
config.read('httpd.conf')

# getfloat() raises an exception if the value is not a float
# getint() and getboolean() also do this for their respective types
somefield = config.get('Section1', 'somefield')
someint = config.getint('Section1', 'someint')
print somefield

XML-RPC Server

You can use SimpleXMLRPCServer to respond to XML-RPC POST requests:
from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler
import sqlite3

# instantiate a server object
server_addr = ('localhost', 8001)
server = SimpleXMLRPCServer (server_addr, SimpleXMLRPCRequestHandler)

# define your methods in a class
class RPCMethods :
    def query (self, q) :
        ....
        return rows

    def execute (self, q) :
        ....
        return success

# start the server
server.register_instance (RPCMethods ())
server.serve_forever ()

XML-RPC Client

You can write a client program to talk to your XML-RPC server using a proxy object (see xmlrpclib.ServerProxy).  Any method you call on the proxy object is automatically encoded as an XML-RPC request and sent to the server:
import xmlrpclib

# connect to your XML-RPC Server
proxy = xmlrpclib.ServerProxy('http://localhost:8001')

# call methods on the server
proxy.execute ('create table test (text)')
proxy.execute ("insert into test values ('hello world')")

# print the results of a query
print proxy.query ('select * from test')


REST APIs

In order to make a REST API, you'll need to implement your own do_GET, do_POST, etc methods and inspect the self.path variable:

from BaseHTTPServer import HTTPServer
from BaseHTTPServer import BaseHTTPRequestHandler
import json

me = {"name": "ryanne"}

class MyRequestHandler (BaseHTTPRequestHandler) :

  def do_GET(self) :

  if self.path == "/me" :
  #send response code:
  self.send_response(200)
  #send headers:
  self.send_header("Content-type:", "text/html")
  # send a blank line to end headers:
  self.wfile.write("\n")

  #send response:
  json.dump(me, self.wfile)

server = HTTPServer(("localhost", 8003), MyRequestHandler)

server.serve_forever()



Comments