发送Multipart / form-data时出现管道故障

时间:2014-08-13 15:30:57

标签: python http curl

我正在尝试设置一个服务器来处理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 个答案:

答案 0 :(得分: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()

另请查看How to handle "100 continue" HTTP message?