From c8d2198976ff5a7542fc9ac2d2a307428f0f2e41 Mon Sep 17 00:00:00 2001 From: jay817 Date: Sat, 5 Oct 2024 22:16:15 -0400 Subject: [PATCH] Update sqlite3-python/README.md --- sqlite3-python/README.md | 33 +++++++++++++-------------------- 1 file changed, 13 insertions(+), 20 deletions(-) diff --git a/sqlite3-python/README.md b/sqlite3-python/README.md index cfc64f0..cf86a49 100644 --- a/sqlite3-python/README.md +++ b/sqlite3-python/README.md @@ -24,29 +24,22 @@ print(list(sql)) # [4] # Cache ```python -class Cache: - def __init__(self): - import sqlite3 - con = sqlite3.connect('fetch.db', isolation_level=None, timeout=1e999) - con.row_factory = sqlite3.Row - self.execute = con.execute +class Fetch: + def __init__(self, db='fetch.db'): + self.con = __import__('sqlite3').connect(db, isolation_level=None) self('PRAGMA busy_timeout='f'{1e9}') self('PRAGMA journal_mode=WAL') self('PRAGMA wal_checkpoint(FULL)') - self('CREATE TABLE IF NOT EXISTS cache(url TEXT PRIMARY KEY, blob BLOB)') - def __call__(self, q, *p): return list(map(dict, self.execute(q, p))) - def __setitem__(self, url, blob): self('INSERT OR REPLACE INTO cache VALUES(?,?)', url, blob) - def __getitem__(self, url): - if blob := self('SELECT blob FROM cache WHERE url=?', url): return blob[0]['blob'] - def __delitem__(self, url): self('DELETE FROM cache WHERE url=?', url) - def __iter__(self): return iter(url['url'] for url in self('SELECT url FROM cache')) - def fetch(self, url): - import urllib.request - if not (blob := self[url]): self[url] = urllib.request.urlopen(url).read() - return self[url] -cache = Cache() -cache.fetch('https://example.com') -print(list(cache)) + self('CREATE TABLE IF NOT EXISTS cache(url PRIMARY KEY, blob)') + def __call__(self, *args): return list(self.con.execute(*args)) + def __getitem__(self, url): + if blob := self('SELECT blob FROM cache WHERE url=?', (url,)): + return blob[0][0] + else: + blob = __import__('urllib').request.urlopen(url).read() + self('INSERT INTO cache VALUES(?,?)', (url, blob)) + return blob +fetch = Fetch() ``` # Class