Writing response body with BaseHTTPRequestHandler

旧巷老猫 提交于 2019-12-20 11:10:32

问题


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

回答1:


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"))



回答2:


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

self.wfile.write(b"<foo>bar</foo>")



回答3:


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



回答4:


Just use this in python3.X

self.wfile.write(bytes("<body><p>This is a test.</p>", "utf-8")


来源:https://stackoverflow.com/questions/7646657/writing-response-body-with-basehttprequesthandler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!