For this project, I'm using a small piece of Python code to return an error 418 to any request. I'm interested in knowing if there is a much smaller piece of code that does the same thing.

#Modfied from code provided by Copyright Jon Berg , turtlemeat.com import string,cgi,time from os import curdir, sep from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
#import pri

class MyHandler(BaseHTTPRequestHandler):

    def do_GET(self):
            self.send_error(418,'I am a Teapot')

def main():
        server = HTTPServer(('', 80), MyHandler)
        print 'started httpserver...'
    except KeyboardInterrupt:
        print '^C received, shutting down server'

if __name__ == '__main__':

PS - I considered putting this on Code Golf SE, but I wasn't sure if single-language-only requests are on-topic.

  • \$\begingroup\$ Why do you want a shorter version? \$\endgroup\$ Feb 10 '12 at 17:26
  • \$\begingroup\$ Oh, well, mainly out of interest and to perhaps illustrate to me that there are much more compact ways that this can be done... \$\endgroup\$
    – Joe
    Feb 11 '12 at 9:42
  • 1
    \$\begingroup\$ Code Golf questions should be asked exclusively on Code Golf and are off-topic here. \$\endgroup\$
    – Adam
    Nov 6 '13 at 12:06

Not really smaller but it will respond to any request, not just GET:

class MyHandler(BaseHTTPRequestHandler):
    def handle_one_request(self):
        self.send_error(418, 'I am a Teapot')

Usually, handle_one_request delegates to the appropriate do_METHOD method, but since we want to treat all of them equal, we may as well not let that delegation take place.

In the interest of making things shorter, you generally don't need the server.socket.close(), unless you plan on restarting a server on that same port right after shutting down this server.


Not the answer you're looking for? Browse other questions tagged or ask your own question.