How to retain cookies for xmlrpc.client in Python 3?

后端 未结 2 505
名媛妹妹
名媛妹妹 2021-01-21 02:32

The default Python xmlrpc.client.Transport (can be used with xmlrpc.client.ServerProxy) does not retain cookies, which are sometimes needed for cookie

2条回答
  •  攒了一身酷
    2021-01-21 03:09

    This is a simple Transport subclass that will retain all cookies:

    class CookiesTransport(xmlrpc.client.Transport):
    """A Transport subclass that retains cookies over its lifetime."""
    
        def __init__(self):
            super().__init__()
            self._cookies = []
    
        def send_headers(self, connection, headers):
            if self._cookies:
                connection.putheader("Cookie", "; ".join(self._cookies))
            super().send_headers(connection, headers)
    
        def parse_response(self, response):
            for header in response.msg.get_all("Set-Cookie"):
                cookie = header.split(";", 1)[0]
                self._cookies.append(cookie)
            return super().parse_response(response)
    

    Usage:

    proxy = xmlrpc.client.ServerProxy(URL, CookiesTransport())
    

    Since xmlrpc.client in Python 3 has better suited hooks for this, it's much simpler than an equivalent Python 2 version.

提交回复
热议问题