11import mysql .connector
22import requests
3+ import sqlite3
4+ import os
35
46
57class API :
@@ -135,16 +137,14 @@ def __init__(self, category, url: str = "https://bpsapi.rajtech.me/", cache_meth
135137 if cache_method is None :
136138 raise ValueError ("Invalid Cache Method" )
137139
138- if cache_method == "sqlite" :
140+ if self . cache_method == "sqlite" :
139141 try :
140142 self .db_name = kwargs ['db_name' ]
141143 self .db_path = kwargs ['db_path' ]
142144 self .db_table = kwargs ['db_table' ]
143145 except KeyError :
144- raise ValueError ("Invalid Database Parameters. One of db_name, db_path, db_table not passed into kwargs" )
145-
146- import sqlite3
147- import os
146+ raise ValueError (
147+ "Invalid Database Parameters. One of db_name, db_path, db_table not passed into kwargs" )
148148
149149 if not os .path .exists (self .db_path + f"/{ self .db_name } .db" ):
150150 os .mkdir (self .db_path )
@@ -162,65 +162,90 @@ def __init__(self, category, url: str = "https://bpsapi.rajtech.me/", cache_meth
162162 self .db_table = kwargs ['db_table' ]
163163
164164 except KeyError :
165- raise ValueError ("Invalid Database Parameters. One of db_name, db_user, db_host, db_port, db_password, db_table not passed into kwargs" )
165+ raise ValueError (
166+ "Invalid Database Parameters. One of db_name, db_user, db_host, db_port, db_password, db_table not passed into kwargs" )
166167
167- self ._con = mysql .connector .python (
168+ self ._con = mysql .connector .connect (
168169 host = self .db_host , port = self .db_port , password = self .db_password ,
169170 user = self .db_user , database = self .db_name ,
170171 )
172+ self ._cur = self ._con .cursor (prepared = True )
171173
172- self ._cur = self ._con .cursor ()
174+ else :
175+ raise Exception ("Invalid cache method. Only mysql and sqlite allowed" )
173176
174177 self ._cur .execute (
175- f"CREATE TABLE IF NOT EXISTS { self .db_table } (category TEXT, id INTEGER, title TEXT, link TEXT)"
178+ f"""
179+ CREATE TABLE IF NOT EXISTS { self .db_table } (
180+ category TEXT,
181+ id INTEGER UNIQUE,
182+ title TEXT,
183+ link TEXT
184+ )
185+ """
176186 )
177187 self ._con .commit ()
178188
179- def get_cache (self ) -> list [list ]:
180- self ._cur .execute (f"SELECT * FROM { self .db_table } WHERE category = ?" , (self .category ,))
189+
190+
191+ def get_cache (self ) -> list [list ] | list :
192+ self ._cur .execute (f"SELECT id, title, link FROM { self .db_table } WHERE category = ?" , (self .category ,))
181193 res = self ._cur .fetchall ()
182194
183195 return res
184196
185197 def _set_cache (self , data ):
186198 # data [ (id, title, link) ]
187- self ._cur .executemany (
188- f"INSERT IGNORE INTO { self .db_table } (category, id, title, link) VALUES ({ self .category } , ?, ?, ?)" ,
189- data
190- )
199+ query = f"INSERT OR IGNORE INTO { self .db_table } (category, id, title, link) VALUES (?, ?, ?, ?)"
200+
201+ if self .cache_method == 'mysql' :
202+ query = query .replace ("OR " , "" )
203+
204+ self ._cur .executemany (query , tuple ((self .category , * d ) for d in data ))
191205 self ._con .commit ()
192206
207+
193208 def _add_to_cache (self , id_ , title , link ):
194- self ._cur .execute (
195- f"INSERT IGNORE INTO { self .db_table } (id, title, link) VALUES (?, ?, ?, ?)" ,
196- (self .category , id_ , title , link )
197- )
209+ query = f"INSERT OR IGNORE INTO { self .db_table } (id, title, link) VALUES (?, ?, ?, ?)"
210+
211+ if self .cache_method == 'mysql' :
212+ query = query .replace ("OR " , "" )
213+
214+ self ._cur .execute (query , (self .category , id_ , title , link ))
198215
199216 def _refresh_cache (self ):
200217 request = requests .get (f"{ self .url } list/{ self .category } " )
201- json = request .json ()
218+ json : dict = request .json ()
202219
203220 try :
204221 json ['http_status' ]
205222 except KeyError :
206223 raise ValueError ("Invalid API Response" )
207224
225+ self ._cur .execute (f"SELECT id FROM { self .db_table } WHERE category = ?" , (self .category ,))
226+ cached_ids : list = self ._cur .fetchall ()
227+ cached_ids : tuple [str , ...] = tuple ([str (i [0 ]) for i in cached_ids ])
228+
208229 if json ['http_status' ] == 200 :
209- self ._set_cache (json ['data' ])
230+ self ._set_cache (
231+ [
232+ (i ['id' ], i ['title' ], i ['link' ])
233+ for i in json ['data' ]
234+ if i ['id' ] not in cached_ids
235+ ]
236+ )
210237
211238 def check (self ) -> list [dict ] | list [None ]:
212- self ._cur .execute (f"SELECT COUNT(*) FROM { self .db_table } WHERE category = ?" , (self .category ,))
213- cached_circular_amount = self ._cur .fetchone ()[0 ]
239+ self ._cur .execute (f"SELECT id FROM { self .db_table } WHERE category = ?" , (self .category ,))
240+
241+ cached_circular_ids = self ._cur .fetchall ()
242+ cached_circular_ids = [i [0 ] for i in cached_circular_ids ]
214243
215244 self ._refresh_cache ()
216245 new_circular_list = self .get_cache ()
217- # data[(id, title, link)]
218-
219- if len (new_circular_list ) != cached_circular_amount :
220- self ._cur .execute (f"SELECT id FROM { self .db_table } WHERE category = ?" , (self .category ,))
246+ # data [(id, title, link)]
221247
222- cached_circular_ids = self ._cur .fetchall ()
223- cached_circular_ids = [i [0 ] for i in cached_circular_ids ]
248+ if len (new_circular_list ) != len (cached_circular_ids ):
224249
225250 new_circular_objects = [i for i in new_circular_list if i [0 ] not in cached_circular_ids ]
226251
0 commit comments