Update code in endpoints/whatsapp.get.py

This commit is contained in:
Backend IM Bot 2025-03-25 13:35:45 +00:00
parent 5af34de2c9
commit f5122459c4

View File

@ -1,31 +1,53 @@
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from core.database import get_db
from models.country import Country
import random
from fastapi import APIRouter, HTTPException
from sqlalchemy import Column, String, Integer
from sqlalchemy.ext.declarative import declarative_base
from typing import List
Base = declarative_base()
class Country(Base):
__tablename__ = "countries"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, unique=True, index=True)
code = Column(String, unique=True)
phone_code = Column(String)
router = APIRouter()
@router.get("/whatsapp")
async def get_random_african_country(db: Session = Depends(get_db)):
"""Get a random African country from database"""
# Query all African countries from database
african_countries = db.query(Country).filter(Country.continent == "Africa").all()
if not african_countries:
raise HTTPException(status_code=404, detail="No African countries found in database")
# Select random country
random_country = random.choice(african_countries)
async def get_countries() -> List[dict]:
"""Get list of countries with phone codes"""
countries = [
{"name": "United States", "code": "US", "phone_code": "+1"},
{"name": "United Kingdom", "code": "GB", "phone_code": "+44"},
{"name": "India", "code": "IN", "phone_code": "+91"}
]
return {
"method": "GET",
"_verb": "get",
"country": {
"name": random_country.name,
"capital": random_country.capital,
"population": random_country.population,
"area": random_country.area
}
}
"countries": countries,
"total": len(countries)
}
# Migration file
"""
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table(
'countries',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('code', sa.String(), nullable=False),
sa.Column('phone_code', sa.String(), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name'),
sa.UniqueConstraint('code')
)
def downgrade():
op.drop_table('countries')
"""