Tuesday, November 2, 2010

Simple Web Server in python

Recently, I was hanging arround flex codes which calls python script resides on other server through web services. I got confused, Is it a good idea to use web service just to call python script from other server? Why not to use cgi module or mod-python to get the same result as getting through web services?

So i decided to write a simple web server which has some methods to be called as a URL. Got excellent help from
http://fragments.turtlemeat.com/pythonwebserver.php
then, i added some code.

        import string,cgi,time
        from os import curdir, sep
        from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

        class VivekServer(BaseHTTPRequestHandler):

            def do_GET(self):
            try:
                if self.path == '/fetch':
                self.send_response(200)
                self.send_header('Content-type',        'text/html')
                self.end_headers()
                res = self.wcount()
                self.wfile.write("Number of count for 'anyword' :")
                self.wfile.write(res[0])
                self.wfile.write(" url is :")
                self.wfile.write(res[1])
                return
                if self.path == '/calculate':           
                self.send_response(200)
                self.send_header('Content-type',        'text/html')
                self.end_headers()
                res = self.calculate()
                for each in res:
                    self.wfile.write(each)
                    self.wfile.write('\n')
                return

                return
               
            except IOError:
                self.send_error(404,'File Not Found: %s' % self.path)
            
            def calculate(self):
            import random
            WORD = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
            data = []
            for i in range(1, 100):
                data.append((random.randrange(0, 1000), random.sample(WORD, len(WORD))[0]))
            return data

            def do_POST(self):
            pass

            def wcount(self):
            from BeautifulSoup import BeautifulSoup as soup
            import urllib2

            htm  = 'http://www.anyurl.com'
            html_text = urllib2.urlopen( htm ) .read()
            sp = soup(html_text)
            idea = sp.findAll( "anyword" )   
            all_a = [ each.get('href') for each in sp.findAll('a') ]
            num = 0
            for each in all_a:
                if each.find("anyword") > 0:
                num=num+1
            return (idea,num,htm)

        def main():
            try:
            server = HTTPServer(('', 7999), VivekServer)
            print 'Server Started.....'
            server.serve_forever()
            except KeyboardInterrupt:
            print 'Server Ends.....'
            server.socket.close()

        if __name__ == '__main__':
            main()

To run above code, just do, python abovecode.py

open web browser, type url as
http://localhost:7999/fetch
http://localhost:7999/calculate

No comments: