Update sqlite3-python/README.md
This commit is contained in:
@@ -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,)):
|
||||||
if blob := self('SELECT blob FROM cache WHERE url=?', url): return blob[0]['blob']
|
return blob[0][0]
|
||||||
def __delitem__(self, url): self('DELETE FROM cache WHERE url=?', url)
|
else:
|
||||||
def __iter__(self): return iter(url['url'] for url in self('SELECT url FROM cache'))
|
blob = __import__('urllib').request.urlopen(url).read()
|
||||||
def fetch(self, url):
|
self('INSERT INTO cache VALUES(?,?)', (url, blob))
|
||||||
import urllib.request
|
return blob
|
||||||
if not (blob := self[url]): self[url] = urllib.request.urlopen(url).read()
|
fetch = Fetch()
|
||||||
return self[url]
|
|
||||||
cache = Cache()
|
|
||||||
cache.fetch('https://example.com')
|
|
||||||
print(list(cache))
|
|
||||||
```
|
```
|
||||||
|
|
||||||
# Class
|
# Class
|
||||||
|
|||||||
Reference in New Issue
Block a user