Writing response body with BaseHTTPRequestHandler

Question:

I’m playing a little with Python 3.2.2 and want to write a simple web server to access some data remotely. This data will be generated by Python so I don’t want to use the SimpleHTTPRequestHandler as it’s a file server, but a handler of my own.

I copied some example from the internet but I’m stuck because the response outputstream refuses to write the body content.

This is my code:

import http.server
import socketserver

PORT = 8000

class MyHandler(http.server.BaseHTTPRequestHandler):
    def do_HEAD(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        print(self.wfile)
        self.wfile.write("<html><head><title>Title goes here.</title></head>")
        self.wfile.write("<body><p>This is a test.</p>")
        # If someone went to "http://something.somewhere.net/foo/bar/",
        # then s.path equals "/foo/bar/".
        self.wfile.write("<p>You accessed path: %s</p>" % self.path)
        self.wfile.write("</body></html>")
        self.wfile.close()

try:
    server = http.server.HTTPServer(('localhost', PORT), MyHandler)
    print('Started http server')
    server.serve_forever()
except KeyboardInterrupt:
    print('^C received, shutting down server')
    server.socket.close()

What should be a correct code for writing the response body?

Thanks a lot.

Edit:

The error is:

...
  File "server.py", line 16, in do_GET
    self.wfile.write("<html><head><title>Title goes here.</title></head>")
  File "C:Python32libsocket.py", line 297, in write
    return self._sock.send(b)
TypeError: 'str' does not support the buffer interface
Asked By: helios

||

Answers:

In Python3 string is a different type than that in Python 2.x. Cast it into bytes using either

self.wfile.write(bytes("<html><head><title>Title goes here.</title></head>/html>","utf-8")) 

or

self.wfile.write("<html><head><title>Title goes here.</title></head></html>".encode("utf-8"))
Answered By: spicavigo

based on your code #comments you’re probably looking for self.headers.getheaders(‘referer’), ie:

if 'http://www.icamefromthissite.com/' in self.headers.getheaders('referer'):
    do something
Answered By: user1054340

For Python 3, prefix the string literals with a b:

self.wfile.write(b"<foo>bar</foo>")
Answered By: Jeenu

Just use this when using Python 3.X

self.wfile.write(bytes("<body><p>This is a test.</p>", "utf-8"))
Answered By: shiv shakti
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.