HTTP POST binary files using Python: concise non-pycurl examples?

前端 未结 5 1205
-上瘾入骨i
-上瘾入骨i 2021-02-06 13:29

I\'m interested in writing a short python script which uploads a short binary file (.wav/.raw audio) via a POST request to a remote server.

I\'ve done this with pycurl,

5条回答
  •  逝去的感伤
    2021-02-06 13:57

    I know this is an old old stack, but I have a different solution.

    If you went thru the trouble of building all the magic headers and everything, and are just UPSET that suddenly a binary file can't pass because python library is mean.. you can monkey patch a solution..

    import httplib
    class HTTPSConnection(httplib.HTTPSConnection):
    def _send_output(self, message_body=None):
        self._buffer.extend(("",""))
        msg = "\r\n".join(self._buffer)
        del self._buffer[:]
        self.send(msg)
        if message_body is not None:
            self.send(message_body)
    
    httplib.HTTPSConnection = HTTPSConnection
    

    If you are using HTTP:// instead of HTTPS:// then replace all instances of HTTPSConnection above with HTTPConnection.

    Before people get upset with me, YES, this is a BAD SOLUTION, but it is a way to fix existing code you really don't want to re-engineer to do it some other way.

    Why does this fix it? Go look at the original Python source, httplib.py file.

提交回复
热议问题