我正在构建一个Python服务器,到目前为止我已经能够检索HTML文件了。。一切都正常运转。但是我的服务器必须打开并检索HTML文件的内容,它将解析HTML中的嵌入链接,如图像、css样式表和js。然后它必须单独连接到web服务器以检索嵌入的文件。i、 e如果网页包含4个图像,则将与web服务器建立总共5个单独的连接,以检索html和4个图像文件。你知道吗
我怎样才能实现这样的场景?你知道吗
这是我的密码:
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()
目前没有回答
相关问题 更多 >
编程相关推荐