簡體   English   中英

Python 3.x BaseHTTPServer或http.server

[英]Python 3.x BaseHTTPServer or http.server

我正在嘗試制作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

問題:是否有一個版本的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”編碼將它們從字符串轉換為字節的方式。 在程序中進行此更改后,您的程序應該可以正常工作。

你可以這樣做:

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

無論誰為http.server做了python 3文檔,都沒有注意到這一變化。 2.7文檔在頂部說明“注意BaseHTTPServer模塊已經合並到Python 3中的http.server.2to3工具將在將源代碼轉換為Python 3時自動調整導入。”

您應該更改wfile參數,因為在Python 3中它接受像對象這樣的字節,因此通過以下方式將字符串轉換為字節:

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

要么

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM