发送Multipart/form-data时出现Broken Pipe错误

0 投票
1 回答
1681 浏览
提问于 2025-04-18 17:10

我正在尝试搭建一个服务器,用来处理Python中的多部分表单数据。我想用curl命令来访问我的Python服务器。

但是我遇到了“Broken Pip Failure”的错误。

有人能帮帮我吗?

PYTHON服务器代码:

from BaseHTTPServer import BaseHTTPRequestHandler
import cgi
import cgitb
cgitb.enable(display=0,logdir="")

class PostHandler(BaseHTTPRequestHandler):

    def do_POST(self):
        print self.headers
        expect = self.headers['Expect']
        self.protocol_version='HTTP/1.1'
        print "Expect %s " % (expect)
        if expect.startswith('100') :
            print "Entered Expect section %s " % (self.protocol_version)
            self.send_response(100)
            print self.protocol_version
            #self.send_header("Content-Length","0")
            self.end_headers()
        else:
            con_length = int(self.headers['Content-Length'])
            print con_length
            content_type = self.headers['Content-Type']
            print content_type
            if content_type.startswith('multipart/form-data') :
                self.send_response(100)
                self.end_headers()
                self.wfile.write("Data:Krishnan");
                #self.rfile.read(con_length)
            else :
                print self.rfile.read(con_length)

                #Send the Response

                self.send_response(200)
                self.end_headers()
                self.wfile.write("Data:Krishnan")
        return

if __name__ == '__main__':
    from BaseHTTPServer import HTTPServer
    server = HTTPServer(('localhost',8000),PostHandler)
    print "Started Serving on HTTP Port 8000"
    server.serve_forever()

用来访问服务器的CURL命令:

curl -iv http://localhost:8000 -F myfile=@"/home/local/krishnan/messages.gz"

CURL的响应:

* About to connect() to localhost port 8000 (#0)
*   Trying 127.0.0.1... connected
> POST / HTTP/1.1
> User-Agent: curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3
> Host: localhost:8000
> Accept: */*
> Content-Length: 4105
> Expect: 100-continue
> Content-Type: multipart/form-data; boundary=----------------------------1ca123daf202
> 
< HTTP/1.1 100 Continue
HTTP/1.1 100 Continue
< Server: BaseHTTP/0.3 Python/2.7.3
Server: BaseHTTP/0.3 Python/2.7.3
< Date: Wed, 13 Aug 2014 15:21:23 GMT
Date: Wed, 13 Aug 2014 15:21:23 GMT

* Send failure: Broken pipe
* Closing connection #0
curl: (55) Send failure: Broken pipe

请帮帮我!

1 个回答

1

当你发现有 Expect:100-continue 这个请求时,你只需要回复一个 100-continue,然后关闭连接。发送完 100-continue 后,你需要读取请求的内容,如果没问题,就回复一个 200 OK

def do_POST(self):
 ....
     self.send_response(100)
     self.end_headers()
     con_length = int(self.headers['Content-Length'])
     data = self.rfile.read(con_length)
     self.send_response(200)
     self.end_headers()

另外,可以看看这个链接:如何处理 "100 continue" 的 HTTP 消息?

撰写回答