本文介绍了如何在Python 3中为xmlrpc.client保留cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认的Python xmlrpc.client.Transport (可与 xmlrpc.client.ServerProxy 一起使用)不会保留基于cookie的登录有时需要的cookie。

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

例如,以下代理与TapaTalk API配合使用(使用cookie进行身份验证),

For example, the following proxy, when used with the TapaTalk API (for which the login method uses cookies for authentication), will give a permission error when trying to modify posts.

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

有,但与Python 3不兼容。

There are some solutions for Python 2 on the net, but they aren't compatible with Python 3.

如何我可以使用保留cookie的运输吗?

How can I use a Transport that retains cookies?

推荐答案

简单的 Transport 子类,将保留所有cookie:

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)

用法:

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

由于Python 3中的 xmlrpc.client 对此更适合,因此它比等效的Python 2版本要简单得多。

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

这篇关于如何在Python 3中为xmlrpc.client保留cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 18:35