Reputation: 30045
I have a simple web server based on BaseHTTPServer
which processes GET
requests (I reuse a previous example below). I would like, for a particular GET parameter (x
in the example below), to open a web page with a simple form and a submit button.
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from urlparse import urlparse, parse_qs
class GetHandler(BaseHTTPRequestHandler):
def do_GET(self):
url = urlparse(self.path)
d = parse_qs(url[4])
if 'x' in d:
self.handle_input_form() # this is the part I want to write
else:
if 'c' in d:
print d['c'][0]
self.send_response(200)
self.end_headers()
return
def handle_input_form(self):
# here a form is displayed, user can input something, submit and
# the content this is handled back to the script for processing
# the next three lines are just a place holder
pass
self.send_response(200)
self.end_headers()
server = HTTPServer(('localhost', 8080), GetHandler)
server.serve_forever()
In other words, this is a self-contained web server (no cgi pages) which I want to keep as simple as possible. I saw a great example of how to use CGI together with the documentation pages, but all assume that there will be a classical cgi-bin structure. Is what I am trying to achieve easy in Python (I am sure it is possible :))?
I would appreciate very much a general answer on best practices ("do it like that" or "don't do it like that" - please keep in mind this is an internal, private server which will not run anything important) as well as the overall flow of handle_input_form()
.
EDIT: Following up on Jon Clements' suggestion I used Bottle and adapted the example in the tutorial:
import bottle
@bottle.get('/note') # or @route('/note')
def note():
return '''
<form action="/note" method="post">
<textarea cols="40" rows="5" name="note">
Some initial text, if needed
</textarea>
<input value="submit" type="submit" />
</form>
'''
@bottle.post('/note') # or @route('/note', method='POST')
def note_update():
note = bottle.request.forms.get('note')
# processing the content of the text frame here
Upvotes: 0
Views: 1160
Reputation: 142216
For something this simple that's also scalable you're better off using a micro-framework such as flask
or bottle
.
Upvotes: 1