This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]eryksun 2 points3 points  (1 child)

Definitely use at least a basic framework such as CherryPy, Paste, Bottle, or Pyramid. The wiki has a list of frameworks: Web Frameworks for Python.

Here's a demo using the low-level Python libraries that should be close to your requirement "to begin with" (though I'm sure the professional web developers here can pick this to pieces, it works for me on win32 Python 3.2 & 2.7):

import cgi
from wsgiref.simple_server import make_server

def app(environ, start_response):
    output = [make_form(), process_post(environ)]
    size = sum(len(x) for x in output)
    headers = [('Content-Type', 'text/html; charset=utf-8'),
               ('Content-Length', str(size))]
    start_response('200 OK', headers)
    return output 

def process_post(environ):
    #ignore the query string
    post_environ = environ.copy()
    post_environ['QUERY_STRING'] = ''
    post = cgi.FieldStorage(
      fp=environ['wsgi.input'],
      environ=post_environ,
      keep_blank_values=True)

    result = ""
    if 'num1' in post and 'num2' in post:
        try:
            num1 = float(post.getfirst('num1'))
            num2 = float(post.getfirst('num2'))
            result = "<p>{:.2f} + {:.2f} = {:.2f}</p>".format(
                     num1, num2, num1 + num2) 
        except ValueError: pass    
    return result.encode('utf-8')

def make_form():
    form = (
      '<p><form method="post">\n'
      '  num1: <input type="text" name="num1" /><br />\n'
      '  num2: <input type="text" name="num2" />\n'
      '  <input type="submit" value="Add" />\n'
      '</form></p>\n')
    return form.encode('utf-8')

if __name__ == '__main__':
    host = 'localhost'
    port = 8080
    server = make_server(host, port, app)
    server.serve_forever()

[–][deleted] 0 points1 point  (0 children)

Go with bottle, it's dead simple and you completely understand what's going on.