ayush2917 commited on
Commit
6f03607
·
verified ·
1 Parent(s): 79a5c87

Update database.py

Browse files
Files changed (1) hide show
  1. database.py +60 -20
database.py CHANGED
@@ -1,50 +1,90 @@
1
  import os
2
  import sqlite3
3
  from flask import g
 
4
 
5
  class Database:
6
  def __init__(self, db_url):
 
 
 
 
7
  self.db_url = db_url
8
  self.conn = None
9
 
 
 
 
 
 
 
10
  def get_db(self):
11
  if not self.conn:
12
- self.conn = sqlite3.connect(self.db_url)
13
- self.conn.row_factory = sqlite3.Row
 
 
 
 
 
 
14
  return self.conn
15
 
16
  def close_db(self):
17
  if self.conn:
18
- self.conn.close()
19
- self.conn = None
 
 
 
 
20
 
21
  def init_db(self):
22
  db = self.get_db()
23
- with open('schema.sql', 'r') as f:
24
- db.cursor().executescript(f.read())
25
- db.commit()
 
 
 
 
 
 
 
 
 
26
 
27
  def cache_news(self, articles):
28
  db = self.get_db()
29
- for article in articles:
30
- try:
31
  db.execute('''
32
  INSERT OR IGNORE INTO news
33
  (title, source, published, url, summary, content)
34
  VALUES (?,?,?,?,?,?)
35
  ''', (
36
- article['title'],
37
- article['source'],
38
- article['published'],
39
- article['url'],
40
- article['summary'],
41
- article['content']
42
  ))
43
- except sqlite3.IntegrityError:
44
- continue
45
- db.commit()
 
 
46
 
47
  def get_cached_news(self):
48
  db = self.get_db()
49
- cur = db.execute('SELECT * FROM news ORDER BY timestamp DESC LIMIT 15')
50
- return [dict(row) for row in cur.fetchall()]
 
 
 
 
 
 
 
 
 
1
  import os
2
  import sqlite3
3
  from flask import g
4
+ from pathlib import Path
5
 
6
  class Database:
7
  def __init__(self, db_url):
8
+ # Ensure the database directory exists
9
+ db_path = self._parse_db_url(db_url)
10
+ Path(db_path).parent.mkdir(parents=True, exist_ok=True)
11
+
12
  self.db_url = db_url
13
  self.conn = None
14
 
15
+ def _parse_db_url(self, db_url):
16
+ """Extract the file path from SQLite URL"""
17
+ if db_url.startswith('sqlite:///'):
18
+ return db_url[10:] # Remove 'sqlite:///'
19
+ return db_url
20
+
21
  def get_db(self):
22
  if not self.conn:
23
+ try:
24
+ self.conn = sqlite3.connect(self._parse_db_url(self.db_url))
25
+ self.conn.row_factory = sqlite3.Row
26
+ # Enable foreign key support
27
+ self.conn.execute("PRAGMA foreign_keys = ON")
28
+ except sqlite3.Error as e:
29
+ print(f"Error connecting to database: {e}")
30
+ raise
31
  return self.conn
32
 
33
  def close_db(self):
34
  if self.conn:
35
+ try:
36
+ self.conn.close()
37
+ except sqlite3.Error as e:
38
+ print(f"Error closing database: {e}")
39
+ finally:
40
+ self.conn = None
41
 
42
  def init_db(self):
43
  db = self.get_db()
44
+ try:
45
+ # Check if schema.sql exists in the correct path
46
+ schema_path = os.path.join(os.path.dirname(__file__), 'schema.sql')
47
+ if not os.path.exists(schema_path):
48
+ raise FileNotFoundError(f"Schema file not found at {schema_path}")
49
+
50
+ with open(schema_path, 'r') as f:
51
+ db.cursor().executescript(f.read())
52
+ db.commit()
53
+ except Exception as e:
54
+ print(f"Error initializing database: {e}")
55
+ raise
56
 
57
  def cache_news(self, articles):
58
  db = self.get_db()
59
+ try:
60
+ for article in articles:
61
  db.execute('''
62
  INSERT OR IGNORE INTO news
63
  (title, source, published, url, summary, content)
64
  VALUES (?,?,?,?,?,?)
65
  ''', (
66
+ article.get('title', ''),
67
+ article.get('source', ''),
68
+ article.get('published', ''),
69
+ article.get('url', ''),
70
+ article.get('summary', ''),
71
+ article.get('content', '')
72
  ))
73
+ db.commit()
74
+ except sqlite3.Error as e:
75
+ print(f"Error caching news: {e}")
76
+ db.rollback()
77
+ raise
78
 
79
  def get_cached_news(self):
80
  db = self.get_db()
81
+ try:
82
+ cur = db.execute('''
83
+ SELECT * FROM news
84
+ ORDER BY published DESC
85
+ LIMIT 15
86
+ ''')
87
+ return [dict(row) for row in cur.fetchall()]
88
+ except sqlite3.Error as e:
89
+ print(f"Error fetching cached news: {e}")
90
+ raise