Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()
like image 646
nunurao Avatar asked Aug 20 '13 23:08

nunurao


1 Answers

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()))
like image 86
Brent Washburne Avatar answered Oct 17 '22 09:10

Brent Washburne