How do I map incoming "path" requests when using HTTPServer?
Asked Answered
N

1

30

I'm fairly new to coding in python. I created a local web server that says "Hello World" and displays the current time.

Is there a way to create a path, without creating a file, on the server program so that when I type in "/time" after 127.0.0.1 in the browser bar, it will display the current time? Likewise if I type "/date" it will give me the current date.

This is what I have so far:

from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
import datetime

port = 80

class myHandler(BaseHTTPRequestHandler):

    #Handler for the GET requests
    def do_GET(self):

    self.send_response(200)
    self.send_header('Content-type','text/html')
    self.end_headers()
    # Send the html message
    self.wfile.write("<b> Hello World !</b>"
                     + "<br><br>Current time and date: " + str(datetime.datetime.now()))

server = HTTPServer(('', port), myHandler)
print 'Started httpserver on port ', port

#Wait forever for incoming http requests
server.serve_forever()
Nonresident answered 20/8, 2013 at 23:32 Comment(0)
E
43

Very simple URL handler:

def do_GET(self):
    if self.path == '/time':
        do_time(self)
    elif self.path == '/date':
        do_date(self)

def do_time(self):
    self.send_response(200)
    self.send_header('Content-type','text/html')
    self.end_headers()
    # Send the html message
    self.wfile.write("<b> Hello World !</b>"
                     + "<br><br>Current time: " + str(datetime.datetime.now()))
Endora answered 20/8, 2013 at 23:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.