简体   繁体   中英

Python http server giving error when connected to

Im getting an error with my server code. It worls till a browser tries to connect to it. I really have no clue what it can be. could any one take a look at it and point me in the right direction?

The error code is

Exception happened during processing of request from ('127.0.0.1', 57953)
Traceback (most recent call last):
  File "C:\Python34\lib\socketserver.py", line 306, in _handle_request_noblock
    self.process_request(request, client_address)
  File "C:\Python34\lib\socketserver.py", line 332, in process_request
    self.finish_request(request, client_address)
  File "C:\Python34\lib\socketserver.py", line 345, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "C:\Python34\lib\socketserver.py", line 666, in __init__
    self.handle()
  File "C:\Python34\lib\http\server.py", line 400, in handle
    self.handle_one_request()
  File "C:\Python34\lib\http\server.py", line 388, in handle_one_request
    method()
  File "C:\Ny mapp\serverpy.py", line 44, in do_GET
    self.wfile.write(f.read())
  File "C:\Python34\lib\socket.py", line 391, in write
    return self._sock.send(b)
TypeError: 'str' does not support the buffer interface

The script

#!/usr/bin/python
from http.server import BaseHTTPRequestHandler,HTTPServer
from os import curdir, sep
import cgi

PORT_NUMBER = 8080

#This class will handles any incoming request from
#the browser 
class myHandler(BaseHTTPRequestHandler):

    #Handler for the GET requests
    def do_GET(self):
        if self.path=="/":
            self.path="/index.html"

        try:
            #Check the file extension required and
            #set the right mime type

            sendReply = False
            if self.path.endswith(".html"):
                mimetype='text/html'
                sendReply = True
            if self.path.endswith(".jpg"):
                mimetype='image/jpg'
                sendReply = True
            if self.path.endswith(".gif"):
                mimetype='image/gif'
                sendReply = True
            if self.path.endswith(".js"):
                mimetype='application/javascript'
                sendReply = True
            if self.path.endswith(".css"):
                mimetype='text/css'
                sendReply = True

            if sendReply == True:
                #Open the static file requested and send it
                f = open(curdir + sep + self.path) 
                self.send_response(200)
                self.send_header('Content-type',mimetype)
                self.end_headers()
                self.wfile.write(f.read())
                f.close()
            return

        except IOError:
            self.send_error(404,'File Not Found: %s' % self.path)

    #Handler for the POST requests
    def do_POST(self):
        if self.path=="/send":
            form = cgi.FieldStorage(
                fp=self.rfile, 
                headers=self.headers,
                environ={'REQUEST_METHOD':'POST',
                         'CONTENT_TYPE':self.headers['Content-Type'],
            })

            print("Your name is: %s" % form["your_name"].value)
            self.send_response(200)
            self.end_headers()
            self.wfile.write("Thanks %s !" % form["your_name"].value)
            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 htto requests
    server.serve_forever()

except KeyboardInterrupt:
    print('^C received, shutting down the web server')
    server.socket.close()

Your error:

TypeError: 'str' does not support the buffer interface

means that in socket , self._sock.send(b) only accepts bytes objects. So you need to send a bytes encoded string.

Try using the following:

def do_GET(self):
    if self.path=="/":
        self.path="/index.html"

    try:
        sendReply = False
        if self.path.endswith(".html"):
            mimetype='text/html'
            sendReply = True
        if self.path.endswith(".jpg"):
            mimetype='image/jpg'
            sendReply = True
        if self.path.endswith(".gif"):
            mimetype='image/gif'
            sendReply = True
        if self.path.endswith(".js"):
            mimetype='application/javascript'
            sendReply = True
        if self.path.endswith(".css"):
            mimetype='text/css'
            sendReply = True

        if sendReply == True:
            #Open the static file requested and send it
            f = open(curdir + sep + self.path) 
            self.send_response(200)
            self.send_header('Content-type',mimetype)
            self.end_headers()

            # save the contents
            read = f.read()
            # write the contents as bytes
            self.wfile.write(bytes(read, 'utf-8'))

            f.close()
        return

    except IOError:
        self.send_error(404,'File Not Found: %s' % self.path)

Use 'rb' . It's OK with webfont(.ttf;.woff;woff2) etc.

f = open(filepath, 'rb')
data = f.read()
self.wfile.write(data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM