在Python服务器

时间:2016-12-02 15:12:26

标签: python sockets http server request

我正在构建一个Python服务器,到目前为止我已经能够检索HTML文件..并且一切正常。但我的服务器必须打开并检索HTML文件的内容,它将解析嵌入式链接的HTML,如图像,css样式表和js。然后,它必须与Web服务器建立单独的连接以检索嵌入的文件。即如果网页包含4个图像,则将对Web服务器进行总共5个单独的连接以检索html和四个图像文件。

我如何实现这种情况?

这是我的代码:

PORT_NUMBER = 50000

class myHandler(BaseHTTPRequestHandler):

    #Handler for the GET requests
    def do_GET(self):
        os.chdir("/Users/hasnain/Desktop/server/document root directory")   #Sets the path to document root directory
        if self.path=="/":# Checks if the request is for root
            self.path="/index.html"# Sets to load index.html if the request is for root            
        try:
            #Check the file extension required and
            #set the right mime type

            sendReply = False
            if self.path.endswith(".html"):
                mimetype='text/html'
                sendReply = True
            if self.path.endswith(".jpg"):
                mimetype='image/jpg'
                sendReply = True
            if self.path.endswith(".gif"):
                mimetype='image/gif'
                sendReply = True
            if self.path.endswith(".js"):
                mimetype='application/javascript'
                sendReply = True
            if self.path.endswith(".css"):
                mimetype='text/css'
                sendReply = True

            if sendReply == True:
                #Open the static file requested and send it
                f = open(curdir + sep + self.path) 
                self.send_response(200)
                self.send_header('Content-type',mimetype)
                self.send_header('Content-length',mimetype)
                self.end_headers()
                self.wfile.write(f.read().encode())
                f.close()
                return

        except IOError:
            self.send_error(404,'File Not Found: %s' % self.path)

try:
    #Create a web server and define the handler to manage the
    #incoming request
    server = HTTPServer(('', PORT_NUMBER), myHandler)
    print ('Started httpserver on port: ' , PORT_NUMBER)

    #Wait forever for incoming htto requests
    server.serve_forever()

except KeyboardInterrupt:
    print ('^C received, shutting down the web server')
    server.socket.close()

0 个答案:

没有答案