Python 3.x BaseHTTPServer 或 http.server

2024-01-30

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

from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer

to:

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

问题:是否有一个版本的 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()

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

error: [Errno 10054] An existing connection was forcibly closed by the remote host

你的 python 3.xx 程序确实可以开箱即用 - 除了一个小问题。问题不在于您的代码,而在于您编写这些行的位置:

self.wfile.write("Hello World !")

您试图在那里写入“字符串”,但字节应该写在那里。所以你需要将字符串转换为字节。

在这里,请参阅我的代码,它与您几乎相同并且运行完美。它是用 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))

请注意我使用“UTF-8”编码将它们从字符串转换为字节的方式。一旦您在程序中进行了此更改,您的程序应该可以正常运行。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python 3.x BaseHTTPServer 或 http.server 的相关文章

随机推荐