Update sqlite3-python/README.md
This commit is contained in:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user