ganeshkumar383 commited on
Commit
5fedf4b
·
verified ·
1 Parent(s): 61a080c

Update db.py

Browse files
Files changed (1) hide show
  1. db.py +38 -23
db.py CHANGED
@@ -1,40 +1,55 @@
1
  import sqlite3
2
- import pandas as pd
3
 
4
- DB_FILE = "trends.db"
5
 
6
  def init_db():
7
  conn = sqlite3.connect(DB_FILE)
8
  c = conn.cursor()
9
- c.execute('''CREATE TABLE IF NOT EXISTS trends_history (
10
- id INTEGER PRIMARY KEY AUTOINCREMENT,
11
- country TEXT,
12
- topic TEXT,
13
- sentiment REAL,
14
- date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
15
- )''')
 
 
16
  conn.commit()
17
  conn.close()
18
 
19
-
20
- def insert_trends(data):
21
  conn = sqlite3.connect(DB_FILE)
22
- df = pd.DataFrame(data)
23
- df.to_sql('trends_history', conn, if_exists='append', index=False)
 
 
 
 
 
24
  conn.close()
25
 
26
-
27
- def get_country_trends(country):
28
  conn = sqlite3.connect(DB_FILE)
29
- query = "SELECT country, topic, sentiment, date FROM trends_history WHERE country=? ORDER BY date DESC LIMIT 100"
30
- df = pd.read_sql_query(query, conn, params=(country,))
 
 
 
 
 
 
31
  conn.close()
32
- return df
33
-
34
 
35
- def get_trend_history():
36
  conn = sqlite3.connect(DB_FILE)
37
- query = "SELECT * FROM trends_history ORDER BY date DESC LIMIT 500"
38
- df = pd.read_sql_query(query, conn)
 
 
 
 
 
39
  conn.close()
40
- return df
 
1
  import sqlite3
2
+ from datetime import datetime
3
 
4
+ DB_FILE = 'data/trends.db'
5
 
6
  def init_db():
7
  conn = sqlite3.connect(DB_FILE)
8
  c = conn.cursor()
9
+ c.execute('''
10
+ CREATE TABLE IF NOT EXISTS trends_history (
11
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
12
+ country TEXT,
13
+ topic TEXT,
14
+ date TIMESTAMP,
15
+ sentiment REAL
16
+ )
17
+ ''')
18
  conn.commit()
19
  conn.close()
20
 
21
+ def insert_trends(country, trends):
 
22
  conn = sqlite3.connect(DB_FILE)
23
+ c = conn.cursor()
24
+ for trend in trends:
25
+ c.execute('''
26
+ INSERT INTO trends_history (country, topic, date, sentiment)
27
+ VALUES (?, ?, ?, ?)
28
+ ''', (country, trend['topic'], datetime.now(), trend['sentiment']))
29
+ conn.commit()
30
  conn.close()
31
 
32
+ def fetch_trends_by_country(country, limit=10):
 
33
  conn = sqlite3.connect(DB_FILE)
34
+ c = conn.cursor()
35
+ c.execute('''
36
+ SELECT topic, sentiment, date FROM trends_history
37
+ WHERE country = ?
38
+ ORDER BY date DESC
39
+ LIMIT ?
40
+ ''', (country, limit))
41
+ rows = c.fetchall()
42
  conn.close()
43
+ return rows
 
44
 
45
+ def fetch_global_trends(limit=10):
46
  conn = sqlite3.connect(DB_FILE)
47
+ c = conn.cursor()
48
+ c.execute('''
49
+ SELECT country, topic, sentiment, date FROM trends_history
50
+ ORDER BY date DESC
51
+ LIMIT ?
52
+ ''', (limit,))
53
+ rows = c.fetchall()
54
  conn.close()
55
+ return rows