pythonbasehttpserverbasehttprequesthandler

BaseHTTPServer only Serves Webpage Once


I'm trying to figure out how to set up a basic web server in Python, but I'm having a lot of difficulty.

My main issue is that I am only able to get my server to serve the webpage once. The html displays a message in the browser and the Javascript displays another message in the console.

When I start the server and go to http://127.0.0.1:8080, both of my messages display and everything is fine. However, I run into problems when I open up a second browser tab and go there again. I get the GET HTTP request in the terminal, but not the GET Javascript request. And nothing displays in either the browser window or the console.

What am I doing wrong? Any suggestions would be appreciated.

Here is my Python code:

import BaseHTTPServer
from os import curdir, sep

htmlfile="htmltest.html"
htmlpage =open(curdir+sep+htmlfile, 'rb')
jsfile="jstest.js"
jspage=open(curdir+sep+jsfile, 'rb')
notfound = "File not found"

class WelcomeHandler(BaseHTTPServer.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 == "/":
            print "get html"
            self.send_response(200)
            self.send_header("Content-type","text/html")
            self.end_headers()
            self.wfile.write(htmlpage.read())
        elif self.path=="/jstest.js":
            print "get js"
            self.send_response(200)
            self.send_header("Content-type","text/js")
            self.end_headers()
            self.wfile.write(jspage.read())
        else:
            self.send_error(404, notfound)

httpserver = BaseHTTPServer.HTTPServer(("127.0.0.1",8080), WelcomeHandler)
#httpserver.serve_forever()
while True:
    httpserver.handle_request()

Solution

  • When you open a file in Python and read its contents, the "file pointer" (i.e. where the next read will start from) is then at the end of the file. You'll either have to re-open it or rewind to the beginning of the file in order to read it again.

    Unless you expect your files to change frequently, you might want to just read them at the start and store the contents in a variable, then serve that. Alternatively, you could move your opening into your do_GET method so it opens it fresh for each request.