Sunday, December 18, 2011

Displaying Calculation Output of Python on Web (customizing)

After success displaying output using python based web, it's normal if we want to display the value of function with a range of variable.

The code below will create web page hosted by Python 2.7 BaseHttpServer module. The page contains list of value of function sin(x)+x**2 at -7<x<7



from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import sys,parser
from math import *
import numpy as np

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        n=10
        x1=-7
        x2=7
        y = 'sin(x)+x**2'
        z = parser.expr(y).compile()
        
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        
        self.wfile.write("Hi Folks, Aravir here")
        self.wfile.write("")
        self.wfile.write("Hi Folks, Aravir here
")
        self.wfile.write("
")
        for i in (range(x1,x2)):
            x=i
            self.wfile.write("The value of ")
            self.wfile.write(y )
            self.wfile.write(" on x = " )
            self.wfile.write(x)
            self.wfile.write(" is " )
            self.wfile.write(eval(z) )
            self.wfile.write("
")
        
        self.wfile.write("")

if __name__=="__main__":
    try:
        server = HTTPServer(("", 8080), Handler)
        server.serve_forever()
    except KeyboardInterrupt:
        server.socket.close()


Here the result in Safari, Mac OS X Lion

From python