How do I map incoming “path” requests when using HTTPServer?

眉间皱痕 提交于 2019-12-20 20:23:46

问题


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()

回答1:


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()))


来源:https://stackoverflow.com/questions/18346583/how-do-i-map-incoming-path-requests-when-using-httpserver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!