chunked_request.py 文件源码

python
阅读 24 收藏 0 点赞 0 评论 0

项目:lddmm-ot 作者: jeanfeydy 项目源码 文件源码
def write(self, data, reconnect_on=('', 200, )):
        ''' Send `data` to the server in chunk-encoded form.
        Check the connection before writing and reconnect
        if disconnected and if the response status code is in `reconnect_on`.

        The response may either be an HTTPResponse object or an empty string.
        '''

        if not self._isconnected():

            # Attempt to get the response.
            response = self._getresponse()

            # Reconnect depending on the status code.
            if ((response == '' and '' in reconnect_on) or
                (response and isinstance(response, http_client.HTTPResponse) and
                 response.status in reconnect_on)):
                self._reconnect()

            elif response and isinstance(response, http_client.HTTPResponse):
                # If an HTTPResponse was recieved then
                # make the users aware instead of
                # auto-reconnecting in case the
                # server is responding with an important
                # message that might prevent
                # future requests from going through,
                # like Invalid Credentials.
                # This allows the user to determine when
                # to reconnect.
                raise Exception("Server responded with "
                                "status code: {status_code}\n"
                                "and message: {msg}."
                                .format(status_code=response.status,
                                        msg=response.read()))

            elif response == '':
                raise Exception("Attempted to write but socket "
                                "was not connected.")

        try:
            msg = data
            msglen = format(len(msg), 'x')  # msg length in hex
            # Send the message in chunk-encoded form
            self._conn.sock.setblocking(1)
            self._conn.send('{msglen}\r\n{msg}\r\n'
                            .format(msglen=msglen, msg=msg).encode('utf-8'))
            self._conn.sock.setblocking(0)
        except http_client.socket.error:
            self._reconnect()
            self.write(data)
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号