Python 3.x BaseHTTPServer或http.server

Lea*_*ner 48 python basehttpserver

我正在尝试制作BaseHTTPServer程序.我更喜欢使用Python 3.3或3.2.我发现该文档很难理解导入的内容,但尝试更改导入:

from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
Run Code Online (Sandbox Code Playgroud)

至:

from http.server import BaseHTTPRequestHandler,HTTPServer
Run Code Online (Sandbox Code Playgroud)

然后导入工作和程序启动并等待GET请求.但是当请求到达时会引发异常:

File "C:\Python33\lib\socket.py", line 317, in write return self._sock.send(b)
TypeError: 'str' does not support the buffer interface
Run Code Online (Sandbox Code Playgroud)

问题:是否有一个版本的BaseHTTPServer或http.server与Python3.x开箱即用,或者我做错了什么?

这是我尝试在Python 3.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()
Run Code Online (Sandbox Code Playgroud)

该程序部分在Python2.7中工作,但在2-8个请求后给出了此异常:

error: [Errno 10054] An existing connection was forcibly closed by the remote host
Run Code Online (Sandbox Code Playgroud)

Ras*_*ash 58

您在python 3.xx中的程序开箱即可使用 - 除了一个小问题.问题不在您的代码中,而是在您编写这些行的位置:

self.wfile.write("Hello World !")
Run Code Online (Sandbox Code Playgroud)

你试图在那里写"字符串",但字节应该去那里.所以你需要将你的字符串转换为字节.

在这里,查看我的代码,它与您几乎完全相同并且完美运行.它用python 3.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))
Run Code Online (Sandbox Code Playgroud)

请注意我使用"UTF-8"编码将它们从字符串转换为字节的方式.在程序中进行此更改后,您的程序应该可以正常工作.


Fra*_*sco 6

你可以这样做:

self.send_header('Content-type','text/html'.encode())
self.end_headers()
# Send the html message
self.wfile.write("Hello World !".encode())
Run Code Online (Sandbox Code Playgroud)


小智 4

无论谁为 http.server 编写了 python 3 文档,都没有注意到这一变化。2.7 文档在顶部指出“注意 BaseHTTPServer 模块已合并到 Python 3 中的 http.server 中。在将源代码转换为 Python 3 时,2to3 工具将自动调整导入。”