Python/decorators

From Wiki
< Python
Revision as of 21:35, 7 December 2018 by Marcluer (talk | contribs) (Die Seite wurde neu angelegt: „== caching HTTP requests == <pre> def persist_to_file(func): def decorator(url, cache=True): filename = url filename = filename.replace(BAS…“)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

caching HTTP requests

def persist_to_file(func):
    def decorator(url, cache=True):
        filename = url
        filename = filename.replace(BASE_URL + "/","")
        filename = filename.replace("/","_")
        filename = filename.replace("?","-")
        filename = CACHE_FOLDER + filename + ".pickle"
        
        if cache == False:
            return func(url)
        
        if os.path.isfile(filename):
            with open (filename, 'rb') as cf:
                content = pickle.load(cf)
            return content
            
        else:
            content = func(url)
            with open(filename, 'wb') as cf:
                pickle.dump(content, cf)
            return content

    return decorator
@persist_to_file
def request_json_api(url):
    """Access API, using username and password. Return JSON"""
    
    response = requests.get(url, auth=(USER, PASS))
    json_data = response.json()
    
    return json_data