0

I'm trying to make a server programer. and the code look like this:

class ALNHTTPRequestHandler(BaseHTTPRequestHandler):
prefix = r'/Users/huxx/PycharmProjects/ServerDemo'
# handle GET command
def do_GET(self):
    rootdir = ALNHTTPRequestHandler.prefix  # file location
    try:
        if self.path.endswith('.html'):
            finalPath = rootdir + self.path
            with open(finalPath, 'rb') as f:
                print('open successed')
            # send code 200 response
                self.send_response(200)
            # send header first
                self.send_header('Content-type', 'text-html')
                self.end_headers()
            # send file content to client
                a = f.read()
                self.wfile.write(a)
                # self.wfile.write(f.read())
                return

    except IOError:
        print('well not found')
        self.send_error(404, 'file not foundbbbb')
def run():
    print('http server is starting...')
    server_address = ('127.0.0.1', 8011)
    httpd = HTTPServer(server_address,ALNHTTPRequestHandler)
    print('http server is running...')
    httpd.serve_forever()


if __name__ == '__main__':
    run()

the problem is if I use self.wfile.write(f.read()) rather than self.wfile.write(a), there's no response at all. Why is that?

1 Answer 1

1

This is related to how the read() method works. First, let's focus on this line:

self.wfile.write(f.read())

read() basically reads through your file-like object (f) and after finishing this method's call the pointer stays at the end of the memory address. You can imagine it as a "read-once" action for the file. After that, the write() call starts and has nothing to write (as the pointer is at the end), therefore there seems to be no response. Now let's have a look at the alternative:

a = f.read()
self.wfile.write(a)

In this case you read the data from f.read() to memory and it stays as a string in a variable a. You can read this variable later as many times as you want (unless you delete it) and this is exactly what subsequent write() call does.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.