我如何映射传入的“路径"?使用HTTPServer时的请求? [英] How do I map incoming "path" requests when using HTTPServer?

查看:163
本文介绍了我如何映射传入的“路径"?使用HTTPServer时的请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用python编码还很陌生.我创建了一个本地网络服务器,上面显示"Hello World"并显示当前时间.

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

是否可以在服务器程序上创建路径而不创建文件,因此当我在浏览器栏中的127.0.0.1之后键入"/time"时,它将显示当前时间?同样,如果我键入"/date",它将给我当前日期.

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

推荐答案

非常简单的URL处理程序:

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

这篇关于我如何映射传入的“路径"?使用HTTPServer时的请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆