简体   繁体   中英

How to use BaseHTTPServer to serve a form in a self-contained server?

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

对于这种既简单又可扩展的东西,最好使用诸如flaskbottle类的微框架。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM