记住SQL查询

Ame*_*ina 7 python memoization pandas joblib

假设我有一个运行SQL查询并返回数据帧的函数:

import pandas.io.sql as psql
import sqlalchemy

query_string = "select a from table;"

def run_my_query(my_query):
    # username, host, port and database are hard-coded here
    engine = sqlalchemy.create_engine('postgresql://{username}@{host}:{port}/{database}'.format(username=username, host=host, port=port, database=database))

    df = psql.read_sql(my_query, engine)
    return df

# Run the query (this is what I want to memoize)
df = run_my_query(my_query)
Run Code Online (Sandbox Code Playgroud)

我想要:

  1. 能够通过每个值的一个缓存条目query_string(即每个查询)记忆我的查询
  2. 能够根据需要强制缓存重置(例如,基于某些标志),例如,如果我认为数据库已更改,我可以更新我的缓存.

我怎么能用joblib,jug做到这一点?

And*_*den 5

是的,你可以用joblib做到这一点(这个例子基本上是自己粘贴的):

>>> from tempfile import mkdtemp
>>> cachedir = mkdtemp()

>>> from joblib import Memory
>>> memory = Memory(cachedir=cachedir, verbose=0)

>>> @memory.cache
... def run_my_query(my_query)
...     ...
...     return df
Run Code Online (Sandbox Code Playgroud)

您可以使用 清除缓存memory.clear()


请注意,您还可以使用lru_cache甚至“手动”使用一个简单的字典:

def run_my_query(my_query, cache={})
    if my_query in cache:
        return cache[my_query]
    ...
    cache[my_query] = df
    return df
Run Code Online (Sandbox Code Playgroud)

可以清除缓存run_my_query.func_defaults[0].clear()(虽然不确定我会推荐这个,只是认为这是一个有趣的例子)。