我正在试着做一个BaseHTTPServer程序。我更喜欢使用Python 3.3或3.2。我发现关于导入什么的文档很难理解,但我尝试从以下位置更改导入:
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer至:
from http.server import BaseHTTPRequestHandler,HTTPServer然后导入工作,程序启动并等待GET请求。但当请求到达时,会引发异常:
File "C:\Python33\lib\socket.py", line 317, in write return self._sock.send(b)
TypeError: 'str' does not support the buffer interface问: Python3.x有没有开箱即用的BaseHTTPServer或http.server版本,还是我做错了什么?
这是我尝试在Python3.3和3.2中运行的“我的”程序:
#!/usr/bin/python
# from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from http.server import BaseHTTPRequestHandler,HTTPServer
PORT_NUMBER = 8080
# This class will handle any incoming request from
# a browser
class myHandler(BaseHTTPRequestHandler):
# Handler for the GET requests
def do_GET(self):
print ('Get request received')
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
# Send the html message
self.wfile.write("Hello World !")
return
try:
# Create a web server and define the handler to manage the
# incoming request
server = HTTPServer(('', PORT_NUMBER), myHandler)
print ('Started httpserver on port ' , PORT_NUMBER)
# Wait forever for incoming http requests
server.serve_forever()
except KeyboardInterrupt:
print ('^C received, shutting down the web server')
server.socket.close()该程序在Python2.7中部分工作,但在2-8个请求后给出了这个例外:
error: [Errno 10054] An existing connection was forcibly closed by the remote host发布于 2014-10-30 20:27:50
你在python3.xx中的程序开箱即用--除了一个小问题。问题不在于你的代码,而在于你写这些代码的地方:
self.wfile.write("Hello World !")你正试图在那里写"string“,但是字节应该放在那里。所以你需要把你的字符串转换成字节。
在这里,请看我的代码,它与您的代码几乎相同,并且可以完美地工作。它是用python3.4编写的
from http.server import BaseHTTPRequestHandler, HTTPServer
import time
hostName = "localhost"
hostPort = 9000
class MyServer(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(bytes("<html><head><title>Title goes here.</title></head>", "utf-8"))
self.wfile.write(bytes("<body><p>This is a test.</p>", "utf-8"))
self.wfile.write(bytes("<p>You accessed path: %s</p>" % self.path, "utf-8"))
self.wfile.write(bytes("</body></html>", "utf-8"))
myServer = HTTPServer((hostName, hostPort), MyServer)
print(time.asctime(), "Server Starts - %s:%s" % (hostName, hostPort))
try:
myServer.serve_forever()
except KeyboardInterrupt:
pass
myServer.server_close()
print(time.asctime(), "Server Stops - %s:%s" % (hostName, hostPort))请注意我使用"UTF-8“编码将它们从字符串转换为字节的方式。一旦你在你的程序中做了这样的改变,你的程序应该工作得很好。
发布于 2016-02-06 21:29:27
你可以这样做:
self.send_header('Content-type','text/html'.encode())
self.end_headers()
# Send the html message
self.wfile.write("Hello World !".encode())发布于 2014-07-28 02:17:29
不管是谁为http.server编写了Python3文档,他都没有注意到这个变化。文档的顶部写道:“请注意,在Python3中,BaseHTTPServer模块已合并到http.server中。当您将源代码转换为Python3时,2to3工具将自动调整导入内容。”
https://stackoverflow.com/questions/23264569
复制相似问题