首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在python中缓存boto3 API调用?

如何在python中缓存boto3 API调用?
EN

Stack Overflow用户
提问于 2019-08-09 19:30:34
回答 2查看 1.3K关注 0票数 1

我正在编写一些代码,这些代码将通过boto3与API进行交互,我正在进行的调用有很大的响应负载,需要一段时间才能处理,在开发过程中测试代码变得非常令人沮丧和不切实际。对于我来说,缓存特定api调用响应的最实际方法是什么,如下面的方法?

代码语言:javascript
复制
#!/usr/bin/python3.6
import boto3

client_cw = boto3.client('cloudwatch')
paginator = client_cw.get_paginator('describe_alarms')

for response in paginator.paginate():
    print(response)

任何帮助都将不胜感激。

EN

回答 2

Stack Overflow用户

发布于 2019-08-14 23:39:37

对于使用unittestmock功能来说,这是一个很好的情况。这允许您重新定义整个对象或对象的特定行为。使用这种方法的解决方案有两部分:

  • 您正在为您的get_paginator()函数定义自定义行为,因此您将模拟boto3.client.get_paginator()方法以返回一个简单的自定义分页器类。
  • 您还需要定义一个简单的自定义分页器类,它只定义一个方法,即您在代码中调用的方法,即paginate(),当该方法被调用时,它应该返回一个硬编码的分页列表( JSON格式),该列表反映了您希望AWS返回的任何内容。

以下是修改后的代码:

代码语言:javascript
复制
#!/usr/bin/python3.6
import boto3
from unittest import mock

client_cw = boto3.client('cloudwatch')

# ---
# This is where the mocking starts
with mock.patch("boto3.client") as client:
    # Create a mock paginator to return mock pages
    class MockPaginator(object):
        def paginate(self):
            # Customize this to whatever the "real"
            # paginated list from AWS looks like
            return [
                {
                    "AlarmsList": [
                        {
                            "Name": "my_alarm_1"
                        },
                        {   
                            "Name": "my_alarm_2"
                        }
                    ]
                }
            ]
    # Tell the get_paginator method to return a fake Paginator
    client.get_paginator.return_value = MockPaginator()
    # This is where the mocking ends
    # (but we're still in the mocking context)
    # ---

    # And now on with the show...
    paginator = client.get_paginator('describe_alarms')
    for response in paginator.paginate():
        print(response)

现在,当您调用paginator.paginate()时,它将返回您在自定义分页器类中提供的自定义硬编码JSON列表,而不是试图调用AWS。

票数 0
EN

Stack Overflow用户

发布于 2021-02-19 15:31:47

我可能要迟到了。但我有一个类似的用例,最后创建了一个名为botocache的项目。你可以在这里查看:- https://github.com/rams3sh/botocache

它使用相同的方法来修补boto3 3的特定方法,使用unittest的补丁。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57436085

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档