Writing response body with BaseHTTPRequestHandler

2020-05-24 20:30发布

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:\Python32\lib\socket.py", line 297, in write
    return self._sock.send(b)
TypeError: 'str' does not support the buffer interface

4条回答
beautiful°
2楼-- · 2020-05-24 21:04

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"))
查看更多
家丑人穷心不美
3楼-- · 2020-05-24 21:12

Just use this when using Python 3.X

self.wfile.write(bytes("<body><p>This is a test.</p>", "utf-8"))
查看更多
\"骚年 ilove
4楼-- · 2020-05-24 21:16

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

self.wfile.write(b"<foo>bar</foo>")
查看更多
霸刀☆藐视天下
5楼-- · 2020-05-24 21:20

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
查看更多
登录 后发表回答