Python 3.x BaseHTTPServer 或 http.server

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23264569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:36:38  来源:igfitidea点击:

Python 3.x BaseHTTPServer or http.server

pythonbasehttpserver

提问by Learner

I am trying to make a BaseHTTPServer program. I prefer to use Python 3.3 or 3.2 for it. I find the doc hard to understand regarding what to import but tried changing the import from:

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

from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer

to:

到:

from http.server import BaseHTTPRequestHandler,HTTPServer

and then the import works and the program start and awaits a GET request. BUT when the request arrives an exception is raised:

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

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

Question: Is there a version of BaseHTTPServer or http.server that works out of the box with Python3.x or am I doing something wrong?

问题:是否有 BaseHTTPServer 或 http.server 的版本可以在 Python3.x 中开箱即用,还是我做错了什么?

This is "my" program that I try running in Python 3.3 and 3.2:

这是我尝试在 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()

The Program work partly in Python2.7 but gives this exception after 2-8 requests:

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

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

回答by rdm

Whoever did the python 3 documentation for http.server failed to note the change. The 2.7 documentation states right at the top "Note The BaseHTTPServer module has been merged into http.server in Python 3. The 2to3 tool will automatically adapt imports when converting your sources to Python 3."

为 http.server 编写 python 3 文档的人没有注意到更改。2.7 文档在顶部声明“注意 BaseHTTPServer 模块已合并到 Python 3 中的 http.server。将源代码转换为 Python 3 时,2to3 工具将自动调整导入。”

回答by Rash

Your program in python 3.xx does work right out of the box - except for one minor problem. The issue is not in your code but the place where you are writing these lines:

您在 python 3.xx 中的程序开箱即用 - 除了一个小问题。问题不在于您的代码,而在于您编写这些行的地方:

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

You are trying to write "string" in there, but bytes should go there. So you need to convert your string to bytes.

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

Here, see my code, which is almost same as you and works perfectly. Its written in python 3.4

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

Please notice the way I convert them from string to bytes using the "UTF-8" encoding. Once you do this change in your program, your program should work fine.

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

回答by Francesco

You can just do like that:

你可以这样做:

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

回答by salafi

You should change wfile argument, because in Python 3 it accept bytes like objects, therefore convert your string to bytes by:

您应该更改 wfile 参数,因为在 Python 3 中它接受像对象这样的字节,因此通过以下方式将您的字符串转换为字节:

self.wfile.write(b"<h1> Hello </h1>)

Or

或者

self.wfile.write( bytes("<h1> Hello </h1>) )

self.wfile.write( bytes("<h1> Hello </h1>) )