使用BaseHTTPRequestHandler编写响应主体

时间:2011-10-04 10:43:05

标签: python basehttprequesthandler

我正在使用Python 3.2.2玩一点,想要编写一个简单的Web服务器来远程访问某些数据。这些数据将由Python生成,所以我不想使用SimpleHTTPRequestHandler,因为它是一个文件服务器,而是我自己的处理程序。

我从互联网上复制了一些例子,但我被卡住了,因为响应输出流拒绝写出正文内容

这是我的代码:

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

编写响应正文的正确代码应该是什么?

非常感谢。

修改

错误是:

...
  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 个答案:

答案 0 :(得分:28)

在Python3中,字符串与Python 2.x中的字符串不同。使用

将其转换为字节
self.wfile.write(bytes("<html><head><title>Title goes here.</title></head>","utf-8") 

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

答案 1 :(得分:5)

对于Python 3,在字符串文字前加上event.shiftKey

b

答案 2 :(得分:3)

基于您的代码#comments,您可能正在寻找self.headers.getheaders('referer'),即:

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

答案 3 :(得分:1)

只需在python3.X中使用它

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