forked from Duff89/parser_avito
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb_service.py
More file actions
69 lines (58 loc) · 2.25 KB
/
Copy pathdb_service.py
File metadata and controls
69 lines (58 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import sqlite3
from models import Item
class SQLiteDBHandler:
"""Работа с БД sqlite"""
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(SQLiteDBHandler, cls).__new__(cls)
return cls._instance
def __init__(self, db_name="database.db"):
if not hasattr(self, "_initialized"):
self.db_name = db_name
self._create_table()
self._initialized = True
def _create_table(self):
"""Создает таблицу viewed, если она не существует."""
with sqlite3.connect(self.db_name) as conn:
cursor = conn.cursor()
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS viewed (
id INTEGER,
price INTEGER
)
"""
)
conn.commit()
def add_record(self, ad: Item):
"""Добавляет новую запись в таблицу viewed."""
with sqlite3.connect(self.db_name) as conn:
cursor = conn.cursor()
cursor.execute(
"INSERT INTO viewed (id, price) VALUES (?, ?)",
(ad.id, ad.priceDetailed.value),
)
conn.commit()
def add_record_from_page(self, ads: list[Item]):
"""Добавляет несколько записей в таблицу viewed."""
records = [(ad.id, ad.priceDetailed.value) for ad in ads]
with sqlite3.connect(self.db_name) as conn:
cursor = conn.cursor()
cursor.executemany(
"""
INSERT OR REPLACE INTO viewed (id, price)
VALUES (?, ?)
""",
records,
)
conn.commit()
def record_exists(self, record_id, price):
"""Проверяет, существует ли запись с заданными id и price."""
with sqlite3.connect(self.db_name) as conn:
cursor = conn.cursor()
cursor.execute(
"SELECT 1 FROM viewed WHERE id = ? AND price = ?",
(record_id, price),
)
return cursor.fetchone() is not None