Fred808 commited on
Commit
6e41c55
·
verified ·
1 Parent(s): 6a002d2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +15 -17
app.py CHANGED
@@ -6,7 +6,7 @@ import base64
6
  import asyncio
7
  from datetime import datetime, timedelta
8
  from bs4 import BeautifulSoup
9
- from sqlalchemy import select
10
  from pydantic import BaseModel
11
 
12
  from fastapi import FastAPI, Request, HTTPException, BackgroundTasks, UploadFile, File, Form
@@ -25,10 +25,10 @@ from sqlalchemy import Column, Integer, String, DateTime, Text, Float
25
  # --- Environment Variables and API Keys ---
26
  SPOONACULAR_API_KEY = os.getenv("SPOONACULAR_API_KEY", "default_fallback_value")
27
  PAYSTACK_SECRET_KEY = os.getenv("PAYSTACK_SECRET_KEY", "default_fallback_value")
28
- DATABASE_URL = os.getenv("DATABASE_URL", "default_fallback_value") # Example using SQLite
29
  NVIDIA_API_KEY = os.getenv("NVIDIA_API_KEY", "default_fallback_value")
30
  openai.api_key = os.getenv("OPENAI_API_KEY", "default_fallback_value")
31
- GOOGLE_MAPS_API_KEY = os.getenv("GOOGLE_MAPS_API_KEY", "default_fallback_value") # Add Google Maps API key
32
 
33
  # WhatsApp Business API credentials (Cloud API)
34
  WHATSAPP_PHONE_NUMBER_ID = os.getenv("WHATSAPP_PHONE_NUMBER_ID", "default_value")
@@ -100,9 +100,13 @@ class OrderTracking(Base):
100
  engine = create_async_engine(DATABASE_URL, echo=True)
101
  async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
102
 
 
103
  async def add_order_ids_column():
104
  async with engine.connect() as conn:
105
- await conn.execute(text("ALTER TABLE user_profiles ADD COLUMN order_ids TEXT DEFAULT ''"))
 
 
 
106
  await conn.commit()
107
  print("Column 'order_ids' added successfully.")
108
 
@@ -111,21 +115,16 @@ async def init_db():
111
  await conn.run_sync(Base.metadata.create_all)
112
  print("Database initialized.")
113
 
114
- # The main function serves as the entry point for our async operations.
115
- async def main():
116
- # Await each coroutine in order
 
 
 
117
  await add_order_ids_column()
118
  await init_db()
119
 
120
- if __name__ == "__main__":
121
- # asyncio.run() creates a new event loop and runs the main() coroutine inside it.
122
- asyncio.run(main())
123
-
124
- async def init_db():
125
- async with engine.begin() as conn:
126
- await conn.run_sync(Base.metadata.create_all)
127
-
128
- # --- Global In-Memory Stores ---
129
  user_state = {} # e.g., { user_id: ConversationState }
130
  conversation_context = {} # { user_id: [ { "timestamp": ..., "role": "user"/"bot", "message": ... }, ... ] }
131
  proactive_timer = {}
@@ -137,7 +136,6 @@ menu_items = [
137
  {"name": "Egusi Soup", "description": "A rich and hearty soup made with melon seeds", "price": 1000, "nutrition": "Calories: 250 kcal, Carbs: 15g, Protein: 8g, Fat: 10g"}
138
  ]
139
 
140
- # --- Conversation State Management ---
141
  SESSION_TIMEOUT = timedelta(minutes=5)
142
 
143
  class ConversationState:
 
6
  import asyncio
7
  from datetime import datetime, timedelta
8
  from bs4 import BeautifulSoup
9
+ from sqlalchemy import select, text # make sure to import text for SQL commands
10
  from pydantic import BaseModel
11
 
12
  from fastapi import FastAPI, Request, HTTPException, BackgroundTasks, UploadFile, File, Form
 
25
  # --- Environment Variables and API Keys ---
26
  SPOONACULAR_API_KEY = os.getenv("SPOONACULAR_API_KEY", "default_fallback_value")
27
  PAYSTACK_SECRET_KEY = os.getenv("PAYSTACK_SECRET_KEY", "default_fallback_value")
28
+ DATABASE_URL = os.getenv("DATABASE_URL", "postgresql+asyncpg://user:password@localhost/dbname") # Update as needed
29
  NVIDIA_API_KEY = os.getenv("NVIDIA_API_KEY", "default_fallback_value")
30
  openai.api_key = os.getenv("OPENAI_API_KEY", "default_fallback_value")
31
+ GOOGLE_MAPS_API_KEY = os.getenv("GOOGLE_MAPS_API_KEY", "default_fallback_value")
32
 
33
  # WhatsApp Business API credentials (Cloud API)
34
  WHATSAPP_PHONE_NUMBER_ID = os.getenv("WHATSAPP_PHONE_NUMBER_ID", "default_value")
 
100
  engine = create_async_engine(DATABASE_URL, echo=True)
101
  async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
102
 
103
+ # --- Migration Functions ---
104
  async def add_order_ids_column():
105
  async with engine.connect() as conn:
106
+ # You can add an existence check if needed.
107
+ await conn.execute(
108
+ text("ALTER TABLE user_profiles ADD COLUMN IF NOT EXISTS order_ids TEXT DEFAULT ''")
109
+ )
110
  await conn.commit()
111
  print("Column 'order_ids' added successfully.")
112
 
 
115
  await conn.run_sync(Base.metadata.create_all)
116
  print("Database initialized.")
117
 
118
+ # --- FastAPI Application Setup ---
119
+ app = FastAPI()
120
+
121
+ # Run migrations at startup
122
+ @app.on_event("startup")
123
+ async def startup_event():
124
  await add_order_ids_column()
125
  await init_db()
126
 
127
+ # --- Global In-Memory Stores and Other Code ---
 
 
 
 
 
 
 
 
128
  user_state = {} # e.g., { user_id: ConversationState }
129
  conversation_context = {} # { user_id: [ { "timestamp": ..., "role": "user"/"bot", "message": ... }, ... ] }
130
  proactive_timer = {}
 
136
  {"name": "Egusi Soup", "description": "A rich and hearty soup made with melon seeds", "price": 1000, "nutrition": "Calories: 250 kcal, Carbs: 15g, Protein: 8g, Fat: 10g"}
137
  ]
138
 
 
139
  SESSION_TIMEOUT = timedelta(minutes=5)
140
 
141
  class ConversationState: