Commit ·
fc36730
1
Parent(s): 014e180
Support PostgreSQL via DATABASE_URL environment variable
Browse filesFiles changed (3)
- app/db/database.py+16-4
- app/main.py+26-35
- requirements.txt+1
1234567891011124 unmodified lines171819from sqlalchemy import create_enginefrom sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy.orm import sessionmakerSQLALCHEMY_DATABASE_URL = "sqlite:///./smart_reader.db"engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)Base = declarative_base()4 unmodified linesyield dbfinally:db.close()12345678910111213141516171819202122234 unmodified lines28293031import osfrom sqlalchemy import create_enginefrom sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy.orm import sessionmakerSQLALCHEMY_DATABASE_URL = os.environ.get("DATABASE_URL", "sqlite:///./smart_reader.db")# Convert postgres:// to postgresql:// if needed for SQLAlchemy 2.0 compatibilityif SQLALCHEMY_DATABASE_URL.startswith("postgres://"):SQLALCHEMY_DATABASE_URL = SQLALCHEMY_DATABASE_URL.replace("postgres://", "postgresql://", 1)if SQLALCHEMY_DATABASE_URL.startswith("sqlite"):engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})else:engine = create_engine(SQLALCHEMY_DATABASE_URL, pool_pre_ping=True)SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)Base = declarative_base()4 unmodified linesyield dbfinally:db.close()
125 unmodified lines126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178125 unmodified lines# --- Auth Endpoints ---def send_verification_email(to_email: str, code: str) -> bool:# For development, just print the code.print(f"\n{'='*40}")print(f"VERIFICATION CODE FOR {to_email}: {code}")print(f"{'='*40}\n")api_key = os.environ.get("BREVO_API_KEY")if not api_key:print("[Brevo Email Error]: BREVO_API_KEY environment variable is not set.")return Falseurl = "https://api.brevo.com/v3/smtp/email"headers = {"accept": "application/json","api-key": api_key,"content-type": "application/json"}payload = {"sender": {"name": "Smart Reader","email": "smartreadercommunity1@gmail.com"},"to": [{"email": to_email}],"subject": "كود تفعيل حسابك - Smart Reader","htmlContent": f"<div dir='rtl' style='font-family: Arial, sans-serif; padding: 25px; background-color: #f4f4f7;'><div style='max-width: 500px; margin: 0 auto; background: #ffffff; padding: 30px; border-radius: 16px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); text-align: center;'><h2 style='color: #4f46e5; margin-bottom: 10px;'>Smart Reader</h2><p style='color: #4b5563; font-size: 16px;'>كود التفعيل الخاص بحسابك هو:</p><div style='background: #eef2ff; border: 2px dashed #6366f1; border-radius: 12px; padding: 15px; margin: 20px 0;'><span style='color: #4338ca; font-size: 32px; font-weight: bold; letter-spacing: 6px;'>{code}</span></div><p style='color: #9ca3af; font-size: 14px;'>هذا الكود صالح لمدة 10 دقائق فقط.</p></div></div>"}try:response = requests.post(url, json=payload, headers=headers, timeout=15)if response.status_code in (200, 201, 202):print(f"[Brevo Email Success] Status Code: {response.status_code}")print(f"[Brevo Email Response Body]: {response.text}")return Trueelse:print(f"[Brevo Email Failure] Status Code: {response.status_code}")print(f"[Brevo Email Response Body]: {response.text}")print(f"[Brevo Email Response Headers]: {dict(response.headers)}")print(f"[Brevo Email Exception Traceback]: None (HTTP Status {response.status_code})")return Falseexcept Exception as e:print(f"[Brevo Email Exception Failure]: {e}")print(f"[Brevo Email Exception Traceback]:\n{traceback.format_exc()}")return False@app.post("/api/v1/auth/request-verification")def request_verification(req: schemas.EmailVerificationRequest, db: Session = Depends(get_db)):125 unmodified lines126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169125 unmodified lines# --- Auth Endpoints ---def send_verification_email(to_email: str, code: str):# For development, just print the code.print(f"\n{'='*40}")print(f"VERIFICATION CODE FOR {to_email}: {code}")print(f"{'='*40}\n")resend_api_key = os.environ.get("RESEND_API_KEY", "re_QUveyqc3_MtpKbD1avSzp9Q9pq7tfnEMN")# Send email via Resend HTTPS REST API (Port 443 - 100% reliable on Cloud)import urllib.requestimport urllib.errorimport jsonurl = "https://api.resend.com/emails"headers = {"Authorization": f"Bearer {resend_api_key}","Content-Type": "application/json"}payload = {"from": "Smart Reader <onboarding@resend.dev>","to": [to_email],"subject": "كود تفعيل حسابك - Smart Reader","html": f"<div dir='rtl' style='font-family: Arial, sans-serif; padding: 25px; background-color: #f4f4f7;'><div style='max-width: 500px; margin: 0 auto; background: #ffffff; padding: 30px; border-radius: 16px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); text-align: center;'><h2 style='color: #4f46e5; margin-bottom: 10px;'>Smart Reader</h2><p style='color: #4b5563; font-size: 16px;'>كود التفعيل الخاص بحسابك هو:</p><div style='background: #eef2ff; border: 2px dashed #6366f1; border-radius: 12px; padding: 15px; margin: 20px 0;'><span style='color: #4338ca; font-size: 32px; font-weight: bold; letter-spacing: 6px;'>{code}</span></div><p style='color: #9ca3af; font-size: 14px;'>هذا الكود صالح لمدة 10 دقائق فقط.</p></div></div>"}try:req = urllib.request.Request(url, data=json.dumps(payload).encode('utf-8'), headers=headers, method='POST')with urllib.request.urlopen(req, timeout=10) as response:res_data = response.read().decode('utf-8')print(f"SUCCESS: Email sent to {to_email} via Resend. Response: {res_data}")except urllib.error.HTTPError as e:try:err_body = e.read().decode('utf-8')except Exception:err_body = "<unable to read body>"print(f"Resend Email HTTPError {e.code} for {to_email}: Body={err_body}")except Exception as e:print(f"Resend Email Error for {to_email}: {e}")@app.post("/api/v1/auth/request-verification")def request_verification(req: schemas.EmailVerificationRequest, db: Session = Depends(get_db)):
12 unmodified lines13141512 unmodified linespasslib==1.7.4bcrypt==4.0.1PyJWT==2.8.012 unmodified lines1314151612 unmodified linespasslib==1.7.4bcrypt==4.0.1PyJWT==2.8.0psycopg2-binary==2.9.10
app/db/database.py+16-4
app/main.py+26-35
requirements.txt+1