Monday, March 9, 2020

saving of requests_cache objects as responses of requests in python, handy for mocking services.

def dump_sqlite_response_cache():
    import sqlite3
    con = sqlite3.connect('demo_cache.sqlite')
    con.row_factory = sqlite3.Row
    from requests_cache.backends.sqlite import DbCache
    import requests_cache
    requests_cache.install_cache('demo_cache')
    #c = BaseCache.remove_old_entries.get_cache()
    s = CachedSession()
    #print(s.__dict__)
    c = requests_cache.core.get_cache()
    #print(c)
    cur = con.cursor()
    cur.execute('select * from responses')
    for i in cur.fetchall():
        cc = i['key']
        ii=0
        with open('response%02d.json' % (ii), 'w+') as f:
            res = c.get_response_and_time(i['key'])
            r = res[0].json()
            f.write(json.dumps(r))
            f.write('\n')
            ii+=1