To start going with my first little Python based web application here I came up with Python Expression Evaluator. What is does ? The name says it all: it evaluates Python expressions, which the user can enter into a form and send to the server where this little 25-liner does its work and returns the result plus all the HTML code to render it nicely on the user’s screen:
It allows the user to type in any type of Python expression, like e.g.
- 80 / 4, or any other type of basic calculation, thus we can use it as a calculator
- len(“Hellow World!”) – we can use it to compute the length of a given string
- “Hello World”.count(“o”) to find out how often a particular character shows up in a given string
- … and many more ( ideas ? )
Here is the code:
Let’s decipher what it does:
- Let the script know we are using Python code
- Import cgitb module and enable CGI Tracebacks to nicely show error messages on the screen rather than in the web server log file. Not really needed here since my little script basically catches all sorts of exceptions, as we will see in a minute. Thanks to Magnus Lie Hetland and his great book “Beginning Python: From Novice to Professional, Second Edition” for this tip !
- Import cgi module, mainly used to retrieve values sent to the server
- Implement the cgi FieldStorage to retrieve values sent to the server
- Evaluate the expression sent to the server. With the help of exception handling all possible exceptions are handled and translated to a message ( variable output ) sent back to the user
- Generate the HTML for the user frontend and insert the output message; either the output from the eval() or the exception message.
Try the expression (“10/0″) to see how Python’s exception handling catches that error. If I would remove my own exception handling from the code and change it from
then the cgitb module would kick in and transform the unhandled exception into a message shown in the browser, like here for example:
Nice, so far.
What enhancements can we think of to enhance this little tool ? Here are my ideas, any more to come ?
- Support multi-line Python code
- Support regular expressions
- Support expression storage & retrieval ( partially works thru your browser; try to hit the Down while entry field has focus )
- Support a more dynamic user interface
- 5. … ?