Merge pull request '(feat): Changed from SQLite3 to PostgreSQL' (#1) from PR1_database_changes into main
Reviewed-on: https://brew.bsd.cafe/RideAware/landing/pulls/1
This commit is contained in:
commit
001c1e5db3
2 changed files with 31 additions and 19 deletions
47
database.py
47
database.py
|
|
@ -1,45 +1,56 @@
|
|||
import sqlite3
|
||||
import os
|
||||
import psycopg2
|
||||
from psycopg2 import IntegrityError
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
DATABASE_URL = os.getenv("DATABASE_FILE")
|
||||
def get_connection():
|
||||
"""Return a database connection."""
|
||||
return psycopg2.connect(
|
||||
host=os.getenv("PG_HOST"),
|
||||
port=os.getenv("PG_PORT"),
|
||||
dbname=os.getenv("PG_DATABASE"),
|
||||
user=os.getenv("PG_USER"),
|
||||
password=os.getenv("PG_PASSWORD"),
|
||||
connect_timeout=10
|
||||
)
|
||||
|
||||
def init_db():
|
||||
conn = sqlite3.connect(DATABASE_URL)
|
||||
conn = get_connection()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("""
|
||||
CREATE TABLE IF NOT EXISTS subscribers (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
id SERIAL PRIMARY KEY,
|
||||
email TEXT UNIQUE NOT NULL
|
||||
)
|
||||
""")
|
||||
conn.commit()
|
||||
cursor.close()
|
||||
conn.close()
|
||||
|
||||
def add_email(email):
|
||||
try:
|
||||
with sqlite3.connect(DATABASE_URL, timeout=10) as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("INSERT INTO subscribers (email) VALUES (?)", (email,))
|
||||
conn.commit()
|
||||
with get_connection() as conn:
|
||||
with conn.cursor() as cursor:
|
||||
cursor.execute("INSERT INTO subscribers (email) VALUES (%s)", (email,))
|
||||
conn.commit()
|
||||
return True
|
||||
except sqlite3.IntegrityError:
|
||||
except IntegrityError:
|
||||
return False
|
||||
except sqlite3.OperationalError as e:
|
||||
print(f"Operational Error: {e}")
|
||||
except psycopg2.OperationalError as e:
|
||||
print(f"Error: {e}")
|
||||
return False
|
||||
|
||||
def remove_email(email):
|
||||
try:
|
||||
with sqlite3.connect(DATABASE_URL, timeout=10) as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("DELETE FROM subscribers WHERE email = ?", (email,))
|
||||
conn.commit()
|
||||
if cursor.rowcount > 0:
|
||||
return True
|
||||
return False
|
||||
with get_connection() as conn:
|
||||
with conn.cursor() as cursor:
|
||||
cursor.execute("DELETE FROM subscribers WHERE email = %s", (email,))
|
||||
conn.commit()
|
||||
if cursor.rowcount > 0:
|
||||
return True
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"Error removing email: {e}")
|
||||
return False
|
||||
|
|
@ -1,2 +1,3 @@
|
|||
flask
|
||||
python-dotenv
|
||||
python-dotenv
|
||||
psycopg2-binary
|
||||
Loading…
Add table
Add a link
Reference in a new issue