Update playwright/README.md
This commit is contained in:
@@ -42,72 +42,66 @@ if __name__ == "__main__":
|
||||
|
||||
```python
|
||||
# db.py
|
||||
|
||||
import sqlite3, json
|
||||
|
||||
import sqlite3, json
|
||||
|
||||
class DB(sqlite3.Connection):
|
||||
def __init__(self, db_name=".db.sqlite"):
|
||||
super().__init__(db_name)
|
||||
with self:
|
||||
cur = self.execute("""
|
||||
self.execute('''
|
||||
CREATE TABLE IF NOT EXISTS kv_store
|
||||
(key TEXT PRIMARY KEY, value BLOB)
|
||||
""")
|
||||
''')
|
||||
|
||||
def __setitem__(self, key, value):
|
||||
value = value if isinstance(value, bytes) else json.dumps(value)
|
||||
with self:
|
||||
cur = self.execute("""
|
||||
result = self.execute('''
|
||||
INSERT OR REPLACE INTO kv_store
|
||||
(key, value) VALUES (?, ?)
|
||||
""", (key, value))
|
||||
return {"modified_count": cur.rowcount}
|
||||
''', (key, value)).rowcount
|
||||
return {"modified_count": result}
|
||||
|
||||
def __getitem__(self, key):
|
||||
with self:
|
||||
cur = self.execute("""
|
||||
result = self.execute('''
|
||||
SELECT value FROM kv_store
|
||||
WHERE key = ?
|
||||
""", (key,))
|
||||
result = cur.fetchone()
|
||||
''', (key,)).fetchone()
|
||||
if result:
|
||||
if isinstance(result[0], str):
|
||||
try:
|
||||
return json.loads(result[0])
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
return result[0]
|
||||
if isinstance(value := result[0], str):
|
||||
try: return json.loads(value)
|
||||
except json.JSONDecodeError: pass
|
||||
return value
|
||||
|
||||
def delete(self, key):
|
||||
with self:
|
||||
cur = self.execute("""
|
||||
result = self.execute('''
|
||||
DELETE FROM kv_store
|
||||
WHERE key = ?
|
||||
""", (key,))
|
||||
return {"deleted_count": cur.rowcount}
|
||||
''', (key,)).rowcount
|
||||
return {"deleted_count": result}
|
||||
|
||||
def keys(self, pattern="*"):
|
||||
pattern = pattern.translate(str.maketrans(
|
||||
{"\\": "\\\\", "%": "\\%", "_": "\\_", "*": "%", "?": "_"}))
|
||||
with self:
|
||||
cur = self.execute("""
|
||||
result = self.execute('''
|
||||
SELECT key FROM kv_store
|
||||
WHERE key LIKE ? ESCAPE '\\'
|
||||
""", (pattern,))
|
||||
result = cur.fetchall()
|
||||
''', (pattern,)).fetchall()
|
||||
return [row[0] for row in result]
|
||||
|
||||
def __repr__(self): return repr(self.keys())
|
||||
|
||||
def exists(self, key):
|
||||
with self:
|
||||
cur = self.execute("""
|
||||
result = self.execute('''
|
||||
SELECT 1 FROM kv_store
|
||||
WHERE key = ?
|
||||
LIMIT 1
|
||||
""", (key,))
|
||||
return bool(cur.fetchone())
|
||||
''', (key,)).fetchone()
|
||||
return bool(result)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user