2014-04-24 19 views
34

Sto provando a creare un programma BaseHTTPServer. Preferisco usare Python 3.3 o 3.2 per questo. Trovo il doc difficile da capire per quanto riguarda cosa importare ma provato a cambiare l'importazione da:Python 3.x BaseHTTPServer o http.server

from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer 

a:

from http.server import BaseHTTPRequestHandler,HTTPServer 

e poi le opere d'importazione e il programma di avvio e attende una richiesta GET. MA quando la richiesta arriva viene sollevata un'eccezione:

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

Domanda: Esiste una versione di BaseHTTPServer o http.server che funziona out of the box con Python3.x o sto facendo qualcosa di sbagliato?

Questo è il "mio" programma che provo in esecuzione in Python 3.3 e 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() 

funzionare il programma in parte in Python2.7 ma dà questa eccezione dopo 2-8 richieste:

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

risposta

1

Chiunque abbia fatto la documentazione di python 3 per http.server non ha notato la modifica. La documentazione 2.7 si afferma in alto "Nota Il modulo BaseHTTPServer è stato fuso in http.server in Python 3. Lo strumento 2to3 adatterà automaticamente le importazioni quando convertono i tuoi sorgenti in Python 3."

+1

Purtroppo, la norma sui Python 3 documenti non notare cambiamenti da Python 2. Penso che questo è stato un grave errore. –

43

Il programma in python 3.xx funziona immediatamente, tranne che per un problema minore. Il problema non è nel codice, ma il luogo in cui si sta scrivendo queste righe:

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

Si sta tentando di scrivere "stringa" in là, ma byte dovrebbe andare lì. Quindi è necessario convertire la stringa in byte.

Qui, guarda il mio codice, che è quasi uguale a te e funziona perfettamente. Il suo scritto in 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)) 

Si prega di notare il modo in cui li converto da stringa a byte utilizzando la codifica "UTF-8". Una volta effettuato questo cambiamento nel programma, il programma dovrebbe funzionare correttamente.

+0

ha funzionato perfettamente per me, grazie! – DenisFLASH

4

si può solo fare così:

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