Update sqlite3-python/README.md
This commit is contained in:
@@ -22,6 +22,33 @@ print(sql[4]) # 2
|
||||
print(list(sql)) # [4]
|
||||
```
|
||||
|
||||
# Cache
|
||||
```python
|
||||
class SQL:
|
||||
def __init__(self):
|
||||
import sqlite3
|
||||
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 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]
|
||||
sql = SQL()
|
||||
sql.fetch('https://example.com')
|
||||
list(sql)
|
||||
```
|
||||
|
||||
# Class
|
||||
```python
|
||||
class SQL:
|
||||
|
||||
Reference in New Issue
Block a user