-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCatFacts.py
More file actions
97 lines (81 loc) · 2.93 KB
/
Copy pathCatFacts.py
File metadata and controls
97 lines (81 loc) · 2.93 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import sqlite3
import requests
import json
# Step 1: Set up the SQLite database and table
def setup_database():
"""
Create an SQLite database and a table to store cat facts if they don't exist.
"""
try:
conn = sqlite3.connect('cat_facts.db') # Connect to SQLite database
cursor = conn.cursor()
# Create a table with columns id, text, and updatedAt
cursor.execute('''
CREATE TABLE IF NOT EXISTS facts2 (
fact TEXT,
length INTEGER
)
''')
conn.commit() # Commit the changes
except sqlite3.Error as e:
print(f"An error occurred while setting up the database: {e}")
finally:
conn.close() # Close the connection
setup_database()
# Step 2: Fetch data from the API
def fetch_cat_facts():
"""
Fetch cat facts from the given API endpoint.
Returns:
list: A list of cat facts in JSON format.
"""
try:
response = requests.get("https://catfact.ninja/facts")
response.raise_for_status() # Raise an HTTPError for bad responses
return response.json()
except requests.RequestException as e:
print(f"An error occurred while fetching data from the API: {e}")
return []
cat_facts = fetch_cat_facts()
# Step 3: Store the data in the SQLite database
def store_cat_facts(facts):
"""
Store the fetched cat facts into the SQLite database.
Args:
facts (list): List of cat facts in JSON format.
"""
try:
conn = sqlite3.connect('cat_facts.db') # Connect to SQLite database
cursor = conn.cursor()
# Insert or replace each cat fact in the database
for fact in facts['data']:
cursor.execute('''
INSERT INTO facts2 (fact, length)
VALUES (?, ?)
''', (fact['fact'], fact['length']))
conn.commit() # Commit the changes
except sqlite3.Error as e:
print(f"An error occurred while storing data in the database: {e}")
finally:
conn.close() # Close the connection
store_cat_facts(cat_facts)
# Step 4: Display the data from the database in the console
def display_cat_facts():
"""
Fetch and display all the cat facts stored in the SQLite database.
"""
try:
conn = sqlite3.connect('cat_facts.db') # Connect to SQLite database
cursor = conn.cursor()
cursor.execute('SELECT * FROM facts2') # Select all rows from the facts table
rows = cursor.fetchall() # Fetch all rows
# Display each row in the console
for row in rows:
print(f"fact: {row[0]}")
print(f"length: {row[1]}")
print("-" * 20)
except sqlite3.Error as e:
print(f"An error occurred while fetching data from the database: {e}")
finally:
conn.close() # Close the connection
display_cat_facts()