Spaces:
Sleeping
Sleeping
Update db.py
Browse files
db.py
CHANGED
|
@@ -1,40 +1,55 @@
|
|
| 1 |
import sqlite3
|
| 2 |
-
|
| 3 |
|
| 4 |
-
DB_FILE =
|
| 5 |
|
| 6 |
def init_db():
|
| 7 |
conn = sqlite3.connect(DB_FILE)
|
| 8 |
c = conn.cursor()
|
| 9 |
-
c.execute('''
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
| 16 |
conn.commit()
|
| 17 |
conn.close()
|
| 18 |
|
| 19 |
-
|
| 20 |
-
def insert_trends(data):
|
| 21 |
conn = sqlite3.connect(DB_FILE)
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
conn.close()
|
| 25 |
|
| 26 |
-
|
| 27 |
-
def get_country_trends(country):
|
| 28 |
conn = sqlite3.connect(DB_FILE)
|
| 29 |
-
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
conn.close()
|
| 32 |
-
return
|
| 33 |
-
|
| 34 |
|
| 35 |
-
def
|
| 36 |
conn = sqlite3.connect(DB_FILE)
|
| 37 |
-
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
conn.close()
|
| 40 |
-
return
|
|
|
|
| 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
|