A tool for light-duty persistent memoization of API calls

Overview

JSON Memoize

What is this?

json_memoize is a straightforward tool for light-duty persistent memoization, created with API calls in mind. It stores the arguments passed to a function and that function call's returned value in a dict, and writes that dict's contents to disk in a .json file.

Arguments at a glance

  • max_age - sets the maximum allowed age in seconds before a cached entry is considered invalid.
  • max_size - sets the maximum number of entries that can be stored in the cache.
  • force_update - overwrites cached values with fresh ones.
  • cache_folder_path - sets the location of the associated .json file.
  • app_name - if no cache_folder_path is provided, app_name is used to create a folder in the default user cache folder.
  • cache_file_name - manually sets the name of the cache file.

Basic Use

Import and add the decorator @memoize to memoize a function.

Warning: json_memoize stores arguments passed to memoized functions in a plain text format. Do not pass your API key, or any other sensitive information, to memoized functions.

Here's a slow api call:

def slow_api_call(arg_1:str, arg_2: str) -> str:
    response = requests.get(f"https://wowthistakesforever.slow/arg-1={arg_1}&arg-2={arg_2}")
    return response.text

Add the @memoize decorator to memoize it.

from json_memoize import memoize

@memoize
def slow_api_call(arg_1:str, arg_2: str) -> str:
    response = requests.get(f"https://wowthistakesforever.slow/arg-1={arg_1}&arg-2={arg_2}")
    return response.text

If the function is called again with the same arguments, the resulting value will be retrieved from the cache without executing the function.

max_age

If you don't want to keep data that's too old, you can set a max age.

@memoize(max_age=600)
def slow_api_call(arg_1:str, arg_2: str) -> str:
    ...

The age of an entry is determined from the time it was first added to the cache. If the difference between that time and the current time exceeds the max_age value, the cached value will be overwritten with a fresh one. Entries that have exceeded max_age will not be written to disk. If max_age is not set, cache entries will not expire. Note: max_age is in seconds. Consider creating variables for measures of time that are inconvenient or unclear when written in seconds, e.g.:

one_week = 604_800
@memoize(max_age=one_week)
    ...

max_size

If you don't want to cache too many entries, you can set a maximum number of entries to store.

@memoize(max_size=10)
def slow_api_call(arg_1:str, arg_2: str) -> str:
    ...

If max_size is set, json_memoize will delete cache entries from oldest to youngest until it meets the specified size limit before it saves the file to disk. As with max_age, the age of an entry is determined by the time at which it was first added to the cache, not when it was most recently used. Note: The size limit is only enforced when the cache file is being written. While the JsonCache object is live in memory, the limit can be exceeded.

force_update

If something in your ecosystem has changed and you want to force the cached values to be updated with fresh information, you can do that too.

@memoize(force_update=True)
def slow_api_call(arg_1:str, arg_2: str) -> str:
    ...

If force_update is True, all entries in the cache will be overwritten, even if they have not yet reached max_age.

Setting the Cache Folder

To reduce the likelihood of name collisions, json_memoize stores its cache files in named folders. There are multiple ways to specify where this folder is located.

Automatic folder creation using app_name

If a value is provided for app_name, json_memoize will use this value to name a new folder within the operating systems preferred user cache folder. e.g.:

@memoize(app_name='my_app') will create a folder structure like ".cache/my_app/"

Manual cache folder assignment

If a cache_folder argument is supplied to the decorator, it will store cache files in that folder. Note: if cache_folder is supplied, it will overrule app_name.

Default folder location

Warning: Not recommended!

If neither cache_folder nor app_name is provided, json_memoize will use its default folder name, yielding a folder structure like ".cache/json_memoize/"

This is not recommended, as intermingling cache files from multiple apps increases the risk of file name collisions, which could cause apps to behave unpredictably.

Naming Cache Files

By default, json_memoize will create each cache file using the name of the function being memoized, e.g.:

@memoize
def slow_api_call():
    ... 

This will create a file called "slow_api_call_cahce.json".

Setting a custom file name with cahce_file_name

If a value is provided for cache_file_name, json_memoize will instead use this value to name the cache file.

Storage and Performance Details

Storage

When a call is made to a memoized function, json_memoize will generate a string from the passed arguments, and use that string as the key in its internal cache dictionary. The value returned by the call is stored as the associated value. Writing this dict to disk is accomplished using json.dump(). Seperate cache files are made for each memoized function.

Warning: It is assumed here that @memoize will be invoked in situations where both the arguments and the returned value of a function have consistent, unambiguous string representations. Passing arguments with unreliable string representation will cause the cache to behave unpredictably. json_memoize will log a warning if it detects something that looks like a repr() output that points to a memory address in an incoming argument. Also, once again, do not pass security-relevant information to memoized functions.

Performance

json_memoize is intended to be performant relative to a slow API call, and has not been optimized further than that. If max_size is exceeded, the entries in the dict are sorted so the oldest ones can be dropped. Setting aside hard drive performance, this sorting operation is the most costly step of the process, and it occurs every time the cahce file is saved.

This is an implementation of NeuronJ work with python.

NeuronJ This is an implementation of NeuronJ work with python. NeuronJ is a plug-in for ImageJ that allows you to create and edit neurons masks. Image

Mohammad Mahdi Samei 3 Aug 28, 2022
Replit theme sync; Github theme sync but in Replit.

This is a Replit theme sync, basically meaning that it keeps track of the current time (which may need to be edited later on), and if the time passes morning, afternoon, etc, the theme switches. The

Glitch 8 Jun 25, 2022
Сервис служит прокси между cервисом регистрации ошибок платформы и системой сбора ошибок Sentry

Sentry Reg Service Сервис служит прокси между Cервисом регистрации ошибок платформы и системой сбора ошибок Sentry. Как развернуть Sentry onpremise. С

Ingvar Vilkman 13 May 24, 2022
Integration of Hotwire's Turbo library with Flask.

turbo-flask Integration of Hotwire's Turbo library with Flask, to allow you to create applications that look and feel like single-page apps without us

Miguel Grinberg 240 Jan 06, 2023
This repository contains a lot of short scripting programs implemented both in Python (Flask) and TypeScript (NodeJS).

fast-scripts This repository contains a lot of short scripting programs implemented both in Python (Flask) and TypeScript (NodeJS). In python These wi

Nahum Maurice 3 Dec 10, 2022
A ULauncher/Albert extension that supports currency, units and date time conversion, as well as a calculator that supports complex numbers and functions.

Ulauncher/Albert Calculate Anything Ulauncher/Albert Calculate Anything is an extension for Ulauncher and Albert to calculate things like currency, ti

tchar 67 Jan 01, 2023
A python package template that can be adapted for RAP projects

Warning - this repository is a snapshot of a repository internal to NHS Digital. This means that links to videos and some URLs may not work. Repositor

NHS Digital 3 Nov 08, 2022
A simple script written using symbolic python that takes as input a desired metric and automatically calculates and outputs the Christoffel Pseudo-Tensor, Riemann Curvature Tensor, Ricci Tensor, Scalar Curvature and the Kretschmann Scalar

A simple script written using symbolic python that takes as input a desired metric and automatically calculates and outputs the Christoffel Pseudo-Tensor, Riemann Curvature Tensor, Ricci Tensor, Scal

2 Nov 27, 2021
A gamey, snakey esoteric programming language

Snak Snak is an esolang based on the classic snake game. Installation You will need python3. To use the visualizer, you will need the curses module. T

David Rutter 3 Oct 10, 2022
Project issue to website data transformation toolkit

braintransform Project issue to website data transformation toolkit. Introduction The purpose of these scripts is to be able to dynamically generate t

Brainhack 1 Nov 19, 2021
Python library to interact with Move Hub / PoweredUp Hubs

Python library to interact with Move Hub / PoweredUp Hubs Move Hub is central controller block of LEGO® Boost Robotics Set. In fact, Move Hub is just

Andrey Pokhilko 499 Jan 04, 2023
Nmap script to detect a Microsoft Exchange instance version with OWA enabled.

Nmap script to detect a Microsoft Exchange instance version with OWA enabled.

Luciano Righetti 27 Nov 17, 2022
MySQL Connectivity based project. Contains various functions of a Store-Management-System

An Intermediate Level Python - MySQL Connectivity based project. Contains various functions of a Store-Management-System.

Yash Wadhvani 2 Nov 21, 2022
objectfactory is a python package to easily implement the factory design pattern for object creation, serialization, and polymorphism

py-object-factory objectfactory is a python package to easily implement the factory design pattern for object creation, serialization, and polymorphis

Devin A. Conley 6 Dec 14, 2022
Minimalistic Gridworld Environment (MiniGrid)

Minimalistic Gridworld Environment (MiniGrid) There are other gridworld Gym environments out there, but this one is designed to be particularly simple

Maxime Chevalier-Boisvert 1.7k Jan 03, 2023
It's an .exe file that can notify your chia profit and warning message every time automatically.

chia-Notify-with-Line 警示程式 It's an .exe file that can notify your chia profit and warning message every time automatically. 這是我自行設計的小程式,有轉成.exe檔了,可以在沒

You,Yu 1 Oct 28, 2021
Service for working with open data of the State Duma of the Russian Federation

Сервис для работы с открытыми данными Госдумы РФ Исходные данные из API Госдумы РФ извлекаются с помощью Apache Nifi и приземляются в хранилище Clickh

Aleksandr Sergeenko 2 Feb 14, 2022
Python-Kite: Simple python code to make kite pattern

Python-Kite Simple python code to make kite pattern. Getting Started These instr

Anoint 0 Mar 22, 2022
Taxonomy addition for complete trees

TACT: Taxonomic Addition for Complete Trees TACT is a Python app for stochastic polytomy resolution. It uses birth-death-sampling estimators across an

Jonathan Chang 3 Jun 07, 2022
Data Orchestration Platform

Table of contents What is DOP Design Concept A Typical DOP Orchestration Flow Prerequisites - Run in Docker For DOP Native Features For DBT Instructio

Datatonic 61 Mar 04, 2022