Update sqlite3-python/README.md

This commit is contained in:
2024-10-05 22:16:15 -04:00
parent 0d5798ff89
commit c8d2198976

View File

@@ -24,29 +24,22 @@ print(list(sql)) # [4]
# Cache # Cache
```python ```python
class Cache: class Fetch:
def __init__(self): def __init__(self, db='fetch.db'):
import sqlite3 self.con = __import__('sqlite3').connect(db, isolation_level=None)
con = sqlite3.connect('fetch.db', isolation_level=None, timeout=1e999)
con.row_factory = sqlite3.Row
self.execute = con.execute
self('PRAGMA busy_timeout='f'{1e9}') self('PRAGMA busy_timeout='f'{1e9}')
self('PRAGMA journal_mode=WAL') self('PRAGMA journal_mode=WAL')
self('PRAGMA wal_checkpoint(FULL)') self('PRAGMA wal_checkpoint(FULL)')
self('CREATE TABLE IF NOT EXISTS cache(url TEXT PRIMARY KEY, blob BLOB)') self('CREATE TABLE IF NOT EXISTS cache(url PRIMARY KEY, blob)')
def __call__(self, q, *p): return list(map(dict, self.execute(q, p))) def __call__(self, *args): return list(self.con.execute(*args))
def __setitem__(self, url, blob): self('INSERT OR REPLACE INTO cache VALUES(?,?)', url, blob)
def __getitem__(self, url): def __getitem__(self, url):
if blob := self('SELECT blob FROM cache WHERE url=?', url): return blob[0]['blob'] if blob := self('SELECT blob FROM cache WHERE url=?', (url,)):
def __delitem__(self, url): self('DELETE FROM cache WHERE url=?', url) return blob[0][0]
def __iter__(self): return iter(url['url'] for url in self('SELECT url FROM cache')) else:
def fetch(self, url): blob = __import__('urllib').request.urlopen(url).read()
import urllib.request self('INSERT INTO cache VALUES(?,?)', (url, blob))
if not (blob := self[url]): self[url] = urllib.request.urlopen(url).read() return blob
return self[url] fetch = Fetch()
cache = Cache()
cache.fetch('https://example.com')
print(list(cache))
``` ```
# Class # Class