【问题标题】:Python http server giving error when connected toPython http服务器连接时出错
【发布时间】:2015-02-28 09:01:00
【问题描述】:

我的服务器代码出错。直到浏览器尝试连接到它为止。我真的不知道它会是什么。任何人都可以看看它并指出我正确的方向吗?

错误代码是

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

脚本

#!/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()

【问题讨论】:

    标签: python http python-3.x server


    【解决方案1】:

    你的错误:

    TypeError: 'str' does not support the buffer interface
    

    表示在socket中,self._sock.send(b)只接受bytes对象。所以你需要发送一个字节编码的字符串。

    尝试使用以下方法:

    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)
    

    【讨论】:

    • Tnx 的答案。我把它改成了你写的,但我得到了一个新的错误。 TypeError:没有编码的字符串参数
    • 没关系让它在缺少 'UTF-8' 的地方工作 self.wfile.write(bytes(read)) 所以我把它改成了 self.wfile.write(bytes(read , 'UTF8' )) Tnx 为您解答。
    【解决方案2】:

    使用'rb'。 webfont(.ttf;.woff;woff2) 等都可以。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-28
      • 2014-09-22
      • 2019-04-22
      • 2014-03-25
      • 2017-02-07
      • 2013-11-08
      • 1970-01-01
      • 2020-09-11
      相关资源
      最近更新 更多