Python BaseHTTPRequestHandler服务器仅适用于第一个GET请求

时间:2019-05-09 04:38:10

标签: python http webserver

我正在尝试基于BaseHTTPRequestHandler创建一个超级基本的python网络服务器。第一次执行对地址127.0.0.1/a的GET请求时,一切正常,并且在浏览器中恢复了图像。

但是,当我第二次重复此GET请求时,我什么也没得到。跟踪代码,我可以看到代码本身正在整个do_GET(self)段中运行。

我真的很困惑为什么Web服务器第一次工作而不是下次工作。

非常感谢您的帮助。

from http.server import BaseHTTPRequestHandler, HTTPServer  
from os import curdir, sep


imagefile = "a.jpg"
imagepage =open(curdir+sep+imagefile, 'rb')

notfound = "File not found"

class webserverHandler(BaseHTTPRequestHandler):
    def do_OPTIONS(self):
        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')                
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header("Access-Control-Allow-Headers", "X-Requested-With") 

    def do_GET(self):
        if self.path == "/a":
            print("getting thg jpg file")
            self.send_response(200)
            self.send_header("Content-type","image/png")
            self.end_headers()
            self.wfile.write(imagepage.read())
    else:
        self.send_error(404, notfound) 

def main():
    try:
        port = 1234
        server = HTTPServer(('127.0.0.1', port), webserverHandler)
        print("Web server is running on port {}".format(port))
        server.serve_forever()

    except KeyboardInterrupt:
        print("^C entered, stopping web server...")

    finally:
        if server:
            print("closing server")
            server.socket.close()


if __name__ == '__main__':
    main()

谢谢!

1 个答案:

答案 0 :(得分:1)

def do_GET(self):
    notfound = "File not found"
    if self.path == "/a":
        print("getting thg jpg file")
        self.send_response(200)
        self.send_header("Content-type","image/png")
        self.end_headers()
        imagefile = "fig1.png"
        imagepage =open(curdir+sep+imagefile, 'rb')
        self.wfile.write(imagepage.read())
    else:
        self.send_error(404, notfound) 

请阅读每个请求中的文件。

原因:
imagepage.read()使文件寻求到图像文件的结尾,因此,我们无法从第二个请求的下一个imagepage.read()读取任何数据。



首先,我们可以使用imageContent = imagepage.read()
我们可以向每个请求发送imageContent     从http.server导入BaseHTTPRequestHandler,HTTPServer
    从os import curdir,sep

imagefile = "fig1.png"
imagepage =open(curdir+sep+imagefile, 'rb')
imageContent = imagepage.read() # Read Image here

notfound = "File not found"

class webserverHandler(BaseHTTPRequestHandler):
    def do_OPTIONS(self):
        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')                
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header("Access-Control-Allow-Headers", "X-Requested-With") 

    def do_GET(self):
        if self.path == "/a":
            print("getting thg jpg file")
            self.send_response(200)
            self.send_header("Content-type","image/png")
            self.end_headers()
            self.wfile.write(imageContent)
        else:
            self.send_error(404, notfound) 

def main():
    try:
        port = 1234
        server = HTTPServer(('127.0.0.1', port), webserverHandler)
        print("Web server is running on port {}".format(port))
        server.serve_forever()

    except KeyboardInterrupt:
        print("^C entered, stopping web server...")

    finally:
        if server:
            print("closing server")
            server.socket.close()


if __name__ == '__main__':
    main()