caching an API response with a configurable refresh time in python

Viewed 20
def get_flows(self):
    return self._ans_api.get_ans(ans_name=self.config.ans).content

The above is a method that I want to cache and it has an api call. How can I set a configurable refresh time for caching it without using 3rd party cache libraries?

1 Answers

You should probably wrap this in a custom class. Something like this:

import requests
import time

class APICache:
    def __init__(self, url, interval=5):
        self._url = url
        self._interval = interval
        self._last_time = 0
        self._text = None

    def get(self):
        if time.time() - self._last_time > self._interval:
            (r := requests.get(self._url)).raise_for_status()
            self._last_time = time.time()
            self._text = r.text
        return self._text

Of course this will probably need to be elaborated to handle headers, authentication etc but this should give you an idea

Related