如何在脚本运行之间存储对象?

2024-10-01 15:46:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用一个基于这个Mint API的python脚本每小时提取一次个人财务信息。你知道吗

要连接到Mint,我需要mint = mintapi.Mint(email, password),它通过selenium打开Chrom实例并登录到Mint,并创建一个<class 'mintapi.api.Mint'>对象

要刷新信息,我只需要执行mint.initiate_account_refresh()。你知道吗

但每次我运行脚本时,它都会再次执行整个登录操作。你知道吗

我可以把mint对象存储在磁盘上,这样我就可以跳过这一步,只刷新帐户了吗?你知道吗


Tags: 对象实例脚本api信息emailseleniumpassword
3条回答

使用库pickle保存和加载对象

保存

import pickle

mint = mintapi.Mint(email, password)
with open('mint .pkl', 'wb') as output:
    pickle.dump(mint , output, pickle.HIGHEST_PROTOCOL)

加载

import pickle

with open('mint.pkl', 'rb') as input:
    mint= pickle.load(input)

mint.initiate_account_refresh()

To store objects in Python you can use the pickle module.

假设您有一个对象mint

import pickle
mint = Something.Somefunc()

with open('data.pickle','wb') as storage:
    pickle.dump(mint,storage)

对象将以二进制字节序列的形式保存在名为data.pickle的文件中。你知道吗

要访问它,只需使用pickle.load()函数。你知道吗

import pickle

with open('data.pickle','rb') as storage:
    mint = pickle.load(storage)

>>>mint
>>><class 'something' object>

注意:

Although it doesn't matter here but the pickle module has a flaw that it can execute some function objects while loading them from a file, so don't use it when reading pickle stored object from a third party source.

啊,开源的奇迹。你知道吗

出于好奇,我去查看了您链接的mintapi,看看是否有什么明显而简单的方法可以让我不用费力的设置来重新创建对象实例。你知道吗

事实证明没有,真的。:(

以下是实例化Mint对象时调用的内容:

def __init__(self, email=None, password=None):
    if email and password:
        self.login_and_get_token(email, password)

如你所见,如果你不给它一个真实的emailpassword,它什么也做不了。(作为旁注,它应该检查is None,但不管怎样)。你知道吗

所以,我们可以避免做过安装过程很好,很容易,但现在我们需要找出如何伪造的安装过程中,根据以前的数据。你知道吗

看看.login_and_get_token(),我们可以看到以下内容:

def login_and_get_token(self, email, password):
    if self.token and self.driver:
        return

    self.driver = get_web_driver(email, password)
    self.token = self.get_token()

又好又简单。如果它已经有了一个令牌,它就完成了,所以它就消失了。如果不是,则设置驱动程序,并通过调用.get_token()来设置.token。你知道吗

这使得整个过程非常容易重写。只需实例化一个Mint对象,没有如下参数:

mint = mintapi.Mint()

然后在其上设置.token

mint.token = 'something magical'

现在你有了一个几乎处于就绪状态的对象。问题是,它基本上依赖于self.driver进行每个方法调用,包括.initiate_account_refresh()

def initiate_account_refresh(self):
    self.post(
        '{}/refreshFILogins.xevent'.format(MINT_ROOT_URL),
        data={'token': self.token},
        headers=JSON_HEADER)

...

def post(self, url, **kwargs):
    return self.driver.request('POST', url, **kwargs)

这看起来像是一个简单的POST,我们可以用一个requests.post()调用来代替它,但我怀疑,当它通过web浏览器执行时,它依赖于某种形式的cookie或会话存储。你知道吗

如果您想进行实验,您可以这样子类Mint

class HeadlessMint(Mint):

    def post(self, url, **kwargs):
        return requests.post(url, **kwargs)

但我的猜测是,随着时间的推移,会有更多的问题浮出水面。你知道吗

好消息是,这个mintapi项目看起来相当简单,重写它使其不依赖于web浏览器对于有一点经验的人来说并不是一个不合理的项目,所以把它放在你的口袋里。你知道吗


至于酸洗,我不相信它会起作用,同样的原因,我不相信子类会起作用-我认为浏览器的存在是重要的。即使您对mint实例进行pickle处理,当您尝试加载它时,它也将丢失其浏览器。你知道吗

最简单的解决方案很可能是将脚本设为长时间运行的脚本,而不是每小时运行一次,它会执行它需要的操作,然后休眠一个小时,然后再执行一次。这样,您就可以在一开始就登录一次,然后它就可以在会话运行期间保持该会话。你知道吗

相关问题 更多 >

    热门问题