Add comprehensive travel app backend with FastAPI
- User authentication with JWT tokens - Trip management with itineraries - Destination database with search functionality - Booking management for flights, hotels, car rentals, activities - SQLite database with Alembic migrations - Health monitoring endpoint - CORS enabled for all origins - Complete API documentation at /docs and /redoc - Environment variable support for SECRET_KEY Requirements for production: - Set SECRET_KEY environment variable
This commit is contained in:
parent
886ca561a7
commit
2cb6659b63
92
README.md
92
README.md
@ -1,3 +1,91 @@
|
||||
# FastAPI Application
|
||||
# Travel App Backend
|
||||
|
||||
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
|
||||
A comprehensive travel planning and booking API built with FastAPI, SQLAlchemy, and SQLite.
|
||||
|
||||
## Features
|
||||
|
||||
- **User Authentication**: JWT-based authentication with registration and login
|
||||
- **Trip Management**: Create, update, and manage travel trips with itineraries
|
||||
- **Destination Database**: Browse and search travel destinations
|
||||
- **Booking Management**: Handle various types of bookings (flights, hotels, car rentals, activities)
|
||||
- **Health Monitoring**: Built-in health check endpoint
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### Authentication
|
||||
- `POST /auth/register` - Register a new user
|
||||
- `POST /auth/login` - Login and get access token
|
||||
- `GET /auth/me` - Get current user information
|
||||
|
||||
### Trips
|
||||
- `POST /trips/` - Create a new trip
|
||||
- `GET /trips/` - Get all user trips
|
||||
- `GET /trips/{trip_id}` - Get specific trip
|
||||
- `PUT /trips/{trip_id}` - Update trip
|
||||
- `DELETE /trips/{trip_id}` - Delete trip
|
||||
- `POST /trips/{trip_id}/itinerary` - Add itinerary item
|
||||
- `GET /trips/{trip_id}/itinerary` - Get trip itinerary
|
||||
|
||||
### Destinations
|
||||
- `GET /destinations/` - Get all destinations (with filters)
|
||||
- `POST /destinations/` - Create new destination
|
||||
- `GET /destinations/{destination_id}` - Get specific destination
|
||||
- `PUT /destinations/{destination_id}` - Update destination
|
||||
- `DELETE /destinations/{destination_id}` - Delete destination
|
||||
- `GET /destinations/search/` - Search destinations
|
||||
|
||||
### Bookings
|
||||
- `POST /bookings/` - Create a new booking
|
||||
- `GET /bookings/` - Get all user bookings (with filters)
|
||||
- `GET /bookings/{booking_id}` - Get specific booking
|
||||
- `PUT /bookings/{booking_id}` - Update booking
|
||||
- `DELETE /bookings/{booking_id}` - Delete booking
|
||||
- `GET /bookings/trip/{trip_id}` - Get all bookings for a trip
|
||||
|
||||
### System
|
||||
- `GET /` - API information
|
||||
- `GET /health` - Health check endpoint
|
||||
- `GET /docs` - Interactive API documentation
|
||||
- `GET /redoc` - Alternative API documentation
|
||||
|
||||
## Installation
|
||||
|
||||
1. Install dependencies:
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
2. Run database migrations:
|
||||
```bash
|
||||
alembic upgrade head
|
||||
```
|
||||
|
||||
3. Start the application:
|
||||
```bash
|
||||
uvicorn main:app --reload
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
Make sure to set the following environment variables:
|
||||
|
||||
- `SECRET_KEY`: JWT secret key for token encryption (required for production)
|
||||
|
||||
## Database
|
||||
|
||||
The application uses SQLite database stored at `/app/storage/db/db.sqlite`.
|
||||
|
||||
## Development
|
||||
|
||||
The project uses Ruff for code formatting and linting. Run:
|
||||
|
||||
```bash
|
||||
ruff check .
|
||||
ruff format .
|
||||
```
|
||||
|
||||
## Documentation
|
||||
|
||||
- API Documentation: http://localhost:8000/docs
|
||||
- Alternative Documentation: http://localhost:8000/redoc
|
||||
- OpenAPI JSON: http://localhost:8000/openapi.json
|
||||
|
41
alembic.ini
Normal file
41
alembic.ini
Normal file
@ -0,0 +1,41 @@
|
||||
[alembic]
|
||||
script_location = alembic
|
||||
prepend_sys_path = .
|
||||
version_path_separator = os
|
||||
sqlalchemy.url = sqlite:////app/storage/db/db.sqlite
|
||||
|
||||
[post_write_hooks]
|
||||
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARN
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARN
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
50
alembic/env.py
Normal file
50
alembic/env.py
Normal file
@ -0,0 +1,50 @@
|
||||
from logging.config import fileConfig
|
||||
from sqlalchemy import engine_from_config
|
||||
from sqlalchemy import pool
|
||||
from alembic import context
|
||||
import sys
|
||||
import os
|
||||
|
||||
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
|
||||
|
||||
from app.db.base import Base
|
||||
|
||||
config = context.config
|
||||
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
target_metadata = Base.metadata
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
url = config.get_main_option("sqlalchemy.url")
|
||||
context.configure(
|
||||
url=url,
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
connectable = engine_from_config(
|
||||
config.get_section(config.config_ini_section),
|
||||
prefix="sqlalchemy.",
|
||||
poolclass=pool.NullPool,
|
||||
)
|
||||
|
||||
with connectable.connect() as connection:
|
||||
context.configure(connection=connection, target_metadata=target_metadata)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
24
alembic/script.py.mako
Normal file
24
alembic/script.py.mako
Normal file
@ -0,0 +1,24 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = ${repr(up_revision)}
|
||||
down_revision = ${repr(down_revision)}
|
||||
branch_labels = ${repr(branch_labels)}
|
||||
depends_on = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
${downgrades if downgrades else "pass"}
|
180
alembic/versions/001_initial_migration.py
Normal file
180
alembic/versions/001_initial_migration.py
Normal file
@ -0,0 +1,180 @@
|
||||
"""Initial migration
|
||||
|
||||
Revision ID: 001
|
||||
Revises:
|
||||
Create Date: 2024-01-01 00:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "001"
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# Create users table
|
||||
op.create_table(
|
||||
"users",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("email", sa.String(), nullable=False),
|
||||
sa.Column("username", sa.String(), nullable=False),
|
||||
sa.Column("full_name", sa.String(), nullable=False),
|
||||
sa.Column("hashed_password", sa.String(), nullable=False),
|
||||
sa.Column("is_active", sa.Boolean(), nullable=True),
|
||||
sa.Column(
|
||||
"created_at",
|
||||
sa.DateTime(timezone=True),
|
||||
server_default=sa.text("(CURRENT_TIMESTAMP)"),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
op.create_index(op.f("ix_users_email"), "users", ["email"], unique=True)
|
||||
op.create_index(op.f("ix_users_id"), "users", ["id"], unique=False)
|
||||
op.create_index(op.f("ix_users_username"), "users", ["username"], unique=True)
|
||||
|
||||
# Create destinations table
|
||||
op.create_table(
|
||||
"destinations",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("name", sa.String(), nullable=False),
|
||||
sa.Column("country", sa.String(), nullable=False),
|
||||
sa.Column("city", sa.String(), nullable=False),
|
||||
sa.Column("description", sa.Text(), nullable=True),
|
||||
sa.Column("latitude", sa.Numeric(precision=10, scale=8), nullable=True),
|
||||
sa.Column("longitude", sa.Numeric(precision=11, scale=8), nullable=True),
|
||||
sa.Column("category", sa.String(), nullable=True),
|
||||
sa.Column("rating", sa.Numeric(precision=3, scale=2), nullable=True),
|
||||
sa.Column("image_url", sa.String(), nullable=True),
|
||||
sa.Column(
|
||||
"created_at",
|
||||
sa.DateTime(timezone=True),
|
||||
server_default=sa.text("(CURRENT_TIMESTAMP)"),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
op.create_index(op.f("ix_destinations_id"), "destinations", ["id"], unique=False)
|
||||
op.create_index(
|
||||
op.f("ix_destinations_name"), "destinations", ["name"], unique=False
|
||||
)
|
||||
|
||||
# Create trips table
|
||||
op.create_table(
|
||||
"trips",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("title", sa.String(), nullable=False),
|
||||
sa.Column("description", sa.Text(), nullable=True),
|
||||
sa.Column("start_date", sa.DateTime(), nullable=False),
|
||||
sa.Column("end_date", sa.DateTime(), nullable=False),
|
||||
sa.Column("budget", sa.Numeric(precision=10, scale=2), nullable=True),
|
||||
sa.Column("status", sa.String(), nullable=True),
|
||||
sa.Column("user_id", sa.Integer(), nullable=False),
|
||||
sa.Column(
|
||||
"created_at",
|
||||
sa.DateTime(timezone=True),
|
||||
server_default=sa.text("(CURRENT_TIMESTAMP)"),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.ForeignKeyConstraint(
|
||||
["user_id"],
|
||||
["users.id"],
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
op.create_index(op.f("ix_trips_id"), "trips", ["id"], unique=False)
|
||||
|
||||
# Create bookings table
|
||||
op.create_table(
|
||||
"bookings",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("booking_type", sa.String(), nullable=False),
|
||||
sa.Column("reference_number", sa.String(), nullable=False),
|
||||
sa.Column("provider", sa.String(), nullable=False),
|
||||
sa.Column("description", sa.Text(), nullable=True),
|
||||
sa.Column("start_date", sa.DateTime(), nullable=False),
|
||||
sa.Column("end_date", sa.DateTime(), nullable=True),
|
||||
sa.Column("total_amount", sa.Numeric(precision=10, scale=2), nullable=False),
|
||||
sa.Column("currency", sa.String(), nullable=True),
|
||||
sa.Column("status", sa.String(), nullable=True),
|
||||
sa.Column("booking_details", sa.Text(), nullable=True),
|
||||
sa.Column("user_id", sa.Integer(), nullable=False),
|
||||
sa.Column("trip_id", sa.Integer(), nullable=True),
|
||||
sa.Column(
|
||||
"created_at",
|
||||
sa.DateTime(timezone=True),
|
||||
server_default=sa.text("(CURRENT_TIMESTAMP)"),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.ForeignKeyConstraint(
|
||||
["trip_id"],
|
||||
["trips.id"],
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["user_id"],
|
||||
["users.id"],
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
op.create_index(op.f("ix_bookings_id"), "bookings", ["id"], unique=False)
|
||||
op.create_index(
|
||||
op.f("ix_bookings_reference_number"),
|
||||
"bookings",
|
||||
["reference_number"],
|
||||
unique=True,
|
||||
)
|
||||
|
||||
# Create itineraries table
|
||||
op.create_table(
|
||||
"itineraries",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("trip_id", sa.Integer(), nullable=False),
|
||||
sa.Column("destination_id", sa.Integer(), nullable=False),
|
||||
sa.Column("day_number", sa.Integer(), nullable=False),
|
||||
sa.Column("activity", sa.String(), nullable=False),
|
||||
sa.Column("description", sa.Text(), nullable=True),
|
||||
sa.Column("start_time", sa.DateTime(), nullable=True),
|
||||
sa.Column("end_time", sa.DateTime(), nullable=True),
|
||||
sa.Column(
|
||||
"created_at",
|
||||
sa.DateTime(timezone=True),
|
||||
server_default=sa.text("(CURRENT_TIMESTAMP)"),
|
||||
nullable=True,
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["destination_id"],
|
||||
["destinations.id"],
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["trip_id"],
|
||||
["trips.id"],
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
op.create_index(op.f("ix_itineraries_id"), "itineraries", ["id"], unique=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index(op.f("ix_itineraries_id"), table_name="itineraries")
|
||||
op.drop_table("itineraries")
|
||||
op.drop_index(op.f("ix_bookings_reference_number"), table_name="bookings")
|
||||
op.drop_index(op.f("ix_bookings_id"), table_name="bookings")
|
||||
op.drop_table("bookings")
|
||||
op.drop_index(op.f("ix_trips_id"), table_name="trips")
|
||||
op.drop_table("trips")
|
||||
op.drop_index(op.f("ix_destinations_name"), table_name="destinations")
|
||||
op.drop_index(op.f("ix_destinations_id"), table_name="destinations")
|
||||
op.drop_table("destinations")
|
||||
op.drop_index(op.f("ix_users_username"), table_name="users")
|
||||
op.drop_index(op.f("ix_users_id"), table_name="users")
|
||||
op.drop_index(op.f("ix_users_email"), table_name="users")
|
||||
op.drop_table("users")
|
0
app/__init__.py
Normal file
0
app/__init__.py
Normal file
0
app/api/__init__.py
Normal file
0
app/api/__init__.py
Normal file
0
app/api/routes/__init__.py
Normal file
0
app/api/routes/__init__.py
Normal file
81
app/api/routes/auth.py
Normal file
81
app/api/routes/auth.py
Normal file
@ -0,0 +1,81 @@
|
||||
from datetime import timedelta
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
|
||||
from sqlalchemy.orm import Session
|
||||
from app.db.session import get_db
|
||||
from app.models.user import User
|
||||
from app.schemas.user import UserCreate, UserResponse, Token
|
||||
from app.auth.security import (
|
||||
verify_password,
|
||||
get_password_hash,
|
||||
create_access_token,
|
||||
verify_token,
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth/login")
|
||||
|
||||
|
||||
def get_user_by_email(db: Session, email: str):
|
||||
return db.query(User).filter(User.email == email).first()
|
||||
|
||||
|
||||
def get_current_user(
|
||||
token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)
|
||||
):
|
||||
email = verify_token(token)
|
||||
user = get_user_by_email(db, email=email)
|
||||
if user is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Could not validate credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
@router.post("/register", response_model=UserResponse)
|
||||
def register_user(user: UserCreate, db: Session = Depends(get_db)):
|
||||
db_user = get_user_by_email(db, email=user.email)
|
||||
if db_user:
|
||||
raise HTTPException(status_code=400, detail="Email already registered")
|
||||
|
||||
db_user = db.query(User).filter(User.username == user.username).first()
|
||||
if db_user:
|
||||
raise HTTPException(status_code=400, detail="Username already taken")
|
||||
|
||||
hashed_password = get_password_hash(user.password)
|
||||
db_user = User(
|
||||
email=user.email,
|
||||
username=user.username,
|
||||
full_name=user.full_name,
|
||||
hashed_password=hashed_password,
|
||||
)
|
||||
db.add(db_user)
|
||||
db.commit()
|
||||
db.refresh(db_user)
|
||||
return db_user
|
||||
|
||||
|
||||
@router.post("/login", response_model=Token)
|
||||
def login_user(
|
||||
form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)
|
||||
):
|
||||
user = get_user_by_email(db, email=form_data.username)
|
||||
if not user or not verify_password(form_data.password, user.hashed_password):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Incorrect email or password",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||
access_token = create_access_token(
|
||||
data={"sub": user.email}, expires_delta=access_token_expires
|
||||
)
|
||||
return {"access_token": access_token, "token_type": "bearer"}
|
||||
|
||||
|
||||
@router.get("/me", response_model=UserResponse)
|
||||
def read_users_me(current_user: User = Depends(get_current_user)):
|
||||
return current_user
|
116
app/api/routes/bookings.py
Normal file
116
app/api/routes/bookings.py
Normal file
@ -0,0 +1,116 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List, Optional
|
||||
from app.db.session import get_db
|
||||
from app.models.user import User
|
||||
from app.models.booking import Booking
|
||||
from app.schemas.booking import BookingCreate, BookingUpdate, BookingResponse
|
||||
from app.api.routes.auth import get_current_user
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/", response_model=BookingResponse)
|
||||
def create_booking(
|
||||
booking: BookingCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
db_booking = Booking(**booking.dict(), user_id=current_user.id)
|
||||
db.add(db_booking)
|
||||
db.commit()
|
||||
db.refresh(db_booking)
|
||||
return db_booking
|
||||
|
||||
|
||||
@router.get("/", response_model=List[BookingResponse])
|
||||
def get_user_bookings(
|
||||
skip: int = 0,
|
||||
limit: int = 100,
|
||||
booking_type: Optional[str] = Query(None),
|
||||
status: Optional[str] = Query(None),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
query = db.query(Booking).filter(Booking.user_id == current_user.id)
|
||||
|
||||
if booking_type:
|
||||
query = query.filter(Booking.booking_type == booking_type)
|
||||
if status:
|
||||
query = query.filter(Booking.status == status)
|
||||
|
||||
bookings = query.offset(skip).limit(limit).all()
|
||||
return bookings
|
||||
|
||||
|
||||
@router.get("/{booking_id}", response_model=BookingResponse)
|
||||
def get_booking(
|
||||
booking_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
booking = (
|
||||
db.query(Booking)
|
||||
.filter(Booking.id == booking_id, Booking.user_id == current_user.id)
|
||||
.first()
|
||||
)
|
||||
if not booking:
|
||||
raise HTTPException(status_code=404, detail="Booking not found")
|
||||
return booking
|
||||
|
||||
|
||||
@router.put("/{booking_id}", response_model=BookingResponse)
|
||||
def update_booking(
|
||||
booking_id: int,
|
||||
booking_update: BookingUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
booking = (
|
||||
db.query(Booking)
|
||||
.filter(Booking.id == booking_id, Booking.user_id == current_user.id)
|
||||
.first()
|
||||
)
|
||||
if not booking:
|
||||
raise HTTPException(status_code=404, detail="Booking not found")
|
||||
|
||||
update_data = booking_update.dict(exclude_unset=True)
|
||||
for field, value in update_data.items():
|
||||
setattr(booking, field, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(booking)
|
||||
return booking
|
||||
|
||||
|
||||
@router.delete("/{booking_id}")
|
||||
def delete_booking(
|
||||
booking_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
booking = (
|
||||
db.query(Booking)
|
||||
.filter(Booking.id == booking_id, Booking.user_id == current_user.id)
|
||||
.first()
|
||||
)
|
||||
if not booking:
|
||||
raise HTTPException(status_code=404, detail="Booking not found")
|
||||
|
||||
db.delete(booking)
|
||||
db.commit()
|
||||
return {"message": "Booking deleted successfully"}
|
||||
|
||||
|
||||
@router.get("/trip/{trip_id}", response_model=List[BookingResponse])
|
||||
def get_trip_bookings(
|
||||
trip_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
bookings = (
|
||||
db.query(Booking)
|
||||
.filter(Booking.trip_id == trip_id, Booking.user_id == current_user.id)
|
||||
.all()
|
||||
)
|
||||
return bookings
|
100
app/api/routes/destinations.py
Normal file
100
app/api/routes/destinations.py
Normal file
@ -0,0 +1,100 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List, Optional
|
||||
from app.db.session import get_db
|
||||
from app.models.destination import Destination
|
||||
from app.schemas.destination import (
|
||||
DestinationCreate,
|
||||
DestinationUpdate,
|
||||
DestinationResponse,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/", response_model=DestinationResponse)
|
||||
def create_destination(destination: DestinationCreate, db: Session = Depends(get_db)):
|
||||
db_destination = Destination(**destination.dict())
|
||||
db.add(db_destination)
|
||||
db.commit()
|
||||
db.refresh(db_destination)
|
||||
return db_destination
|
||||
|
||||
|
||||
@router.get("/", response_model=List[DestinationResponse])
|
||||
def get_destinations(
|
||||
skip: int = 0,
|
||||
limit: int = 100,
|
||||
country: Optional[str] = Query(None),
|
||||
category: Optional[str] = Query(None),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
query = db.query(Destination)
|
||||
|
||||
if country:
|
||||
query = query.filter(Destination.country.ilike(f"%{country}%"))
|
||||
if category:
|
||||
query = query.filter(Destination.category == category)
|
||||
|
||||
destinations = query.offset(skip).limit(limit).all()
|
||||
return destinations
|
||||
|
||||
|
||||
@router.get("/{destination_id}", response_model=DestinationResponse)
|
||||
def get_destination(destination_id: int, db: Session = Depends(get_db)):
|
||||
destination = db.query(Destination).filter(Destination.id == destination_id).first()
|
||||
if not destination:
|
||||
raise HTTPException(status_code=404, detail="Destination not found")
|
||||
return destination
|
||||
|
||||
|
||||
@router.put("/{destination_id}", response_model=DestinationResponse)
|
||||
def update_destination(
|
||||
destination_id: int,
|
||||
destination_update: DestinationUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
destination = db.query(Destination).filter(Destination.id == destination_id).first()
|
||||
if not destination:
|
||||
raise HTTPException(status_code=404, detail="Destination not found")
|
||||
|
||||
update_data = destination_update.dict(exclude_unset=True)
|
||||
for field, value in update_data.items():
|
||||
setattr(destination, field, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(destination)
|
||||
return destination
|
||||
|
||||
|
||||
@router.delete("/{destination_id}")
|
||||
def delete_destination(destination_id: int, db: Session = Depends(get_db)):
|
||||
destination = db.query(Destination).filter(Destination.id == destination_id).first()
|
||||
if not destination:
|
||||
raise HTTPException(status_code=404, detail="Destination not found")
|
||||
|
||||
db.delete(destination)
|
||||
db.commit()
|
||||
return {"message": "Destination deleted successfully"}
|
||||
|
||||
|
||||
@router.get("/search/", response_model=List[DestinationResponse])
|
||||
def search_destinations(
|
||||
q: str = Query(..., description="Search query"),
|
||||
skip: int = 0,
|
||||
limit: int = 100,
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
destinations = (
|
||||
db.query(Destination)
|
||||
.filter(
|
||||
(Destination.name.ilike(f"%{q}%"))
|
||||
| (Destination.city.ilike(f"%{q}%"))
|
||||
| (Destination.country.ilike(f"%{q}%"))
|
||||
| (Destination.description.ilike(f"%{q}%"))
|
||||
)
|
||||
.offset(skip)
|
||||
.limit(limit)
|
||||
.all()
|
||||
)
|
||||
return destinations
|
150
app/api/routes/trips.py
Normal file
150
app/api/routes/trips.py
Normal file
@ -0,0 +1,150 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List
|
||||
from app.db.session import get_db
|
||||
from app.models.user import User
|
||||
from app.models.trip import Trip, Itinerary
|
||||
from app.schemas.trip import (
|
||||
TripCreate,
|
||||
TripUpdate,
|
||||
TripResponse,
|
||||
ItineraryCreate,
|
||||
ItineraryResponse,
|
||||
)
|
||||
from app.api.routes.auth import get_current_user
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/", response_model=TripResponse)
|
||||
def create_trip(
|
||||
trip: TripCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
db_trip = Trip(**trip.dict(), user_id=current_user.id)
|
||||
db.add(db_trip)
|
||||
db.commit()
|
||||
db.refresh(db_trip)
|
||||
return db_trip
|
||||
|
||||
|
||||
@router.get("/", response_model=List[TripResponse])
|
||||
def get_user_trips(
|
||||
skip: int = 0,
|
||||
limit: int = 100,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
trips = (
|
||||
db.query(Trip)
|
||||
.filter(Trip.user_id == current_user.id)
|
||||
.offset(skip)
|
||||
.limit(limit)
|
||||
.all()
|
||||
)
|
||||
return trips
|
||||
|
||||
|
||||
@router.get("/{trip_id}", response_model=TripResponse)
|
||||
def get_trip(
|
||||
trip_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
trip = (
|
||||
db.query(Trip)
|
||||
.filter(Trip.id == trip_id, Trip.user_id == current_user.id)
|
||||
.first()
|
||||
)
|
||||
if not trip:
|
||||
raise HTTPException(status_code=404, detail="Trip not found")
|
||||
return trip
|
||||
|
||||
|
||||
@router.put("/{trip_id}", response_model=TripResponse)
|
||||
def update_trip(
|
||||
trip_id: int,
|
||||
trip_update: TripUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
trip = (
|
||||
db.query(Trip)
|
||||
.filter(Trip.id == trip_id, Trip.user_id == current_user.id)
|
||||
.first()
|
||||
)
|
||||
if not trip:
|
||||
raise HTTPException(status_code=404, detail="Trip not found")
|
||||
|
||||
update_data = trip_update.dict(exclude_unset=True)
|
||||
for field, value in update_data.items():
|
||||
setattr(trip, field, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(trip)
|
||||
return trip
|
||||
|
||||
|
||||
@router.delete("/{trip_id}")
|
||||
def delete_trip(
|
||||
trip_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
trip = (
|
||||
db.query(Trip)
|
||||
.filter(Trip.id == trip_id, Trip.user_id == current_user.id)
|
||||
.first()
|
||||
)
|
||||
if not trip:
|
||||
raise HTTPException(status_code=404, detail="Trip not found")
|
||||
|
||||
db.delete(trip)
|
||||
db.commit()
|
||||
return {"message": "Trip deleted successfully"}
|
||||
|
||||
|
||||
@router.post("/{trip_id}/itinerary", response_model=ItineraryResponse)
|
||||
def add_itinerary_item(
|
||||
trip_id: int,
|
||||
itinerary: ItineraryCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
trip = (
|
||||
db.query(Trip)
|
||||
.filter(Trip.id == trip_id, Trip.user_id == current_user.id)
|
||||
.first()
|
||||
)
|
||||
if not trip:
|
||||
raise HTTPException(status_code=404, detail="Trip not found")
|
||||
|
||||
db_itinerary = Itinerary(**itinerary.dict(), trip_id=trip_id)
|
||||
db.add(db_itinerary)
|
||||
db.commit()
|
||||
db.refresh(db_itinerary)
|
||||
return db_itinerary
|
||||
|
||||
|
||||
@router.get("/{trip_id}/itinerary", response_model=List[ItineraryResponse])
|
||||
def get_trip_itinerary(
|
||||
trip_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
trip = (
|
||||
db.query(Trip)
|
||||
.filter(Trip.id == trip_id, Trip.user_id == current_user.id)
|
||||
.first()
|
||||
)
|
||||
if not trip:
|
||||
raise HTTPException(status_code=404, detail="Trip not found")
|
||||
|
||||
itinerary = (
|
||||
db.query(Itinerary)
|
||||
.filter(Itinerary.trip_id == trip_id)
|
||||
.order_by(Itinerary.day_number, Itinerary.start_time)
|
||||
.all()
|
||||
)
|
||||
return itinerary
|
0
app/auth/__init__.py
Normal file
0
app/auth/__init__.py
Normal file
50
app/auth/security.py
Normal file
50
app/auth/security.py
Normal file
@ -0,0 +1,50 @@
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional
|
||||
from jose import JWTError, jwt
|
||||
from passlib.context import CryptContext
|
||||
from fastapi import HTTPException, status
|
||||
import os
|
||||
|
||||
SECRET_KEY = os.getenv("SECRET_KEY", "your-secret-key-change-in-production")
|
||||
ALGORITHM = "HS256"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES = 30
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
|
||||
|
||||
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||
return pwd_context.verify(plain_password, hashed_password)
|
||||
|
||||
|
||||
def get_password_hash(password: str) -> str:
|
||||
return pwd_context.hash(password)
|
||||
|
||||
|
||||
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
|
||||
to_encode = data.copy()
|
||||
if expires_delta:
|
||||
expire = datetime.utcnow() + expires_delta
|
||||
else:
|
||||
expire = datetime.utcnow() + timedelta(minutes=15)
|
||||
to_encode.update({"exp": expire})
|
||||
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
||||
return encoded_jwt
|
||||
|
||||
|
||||
def verify_token(token: str):
|
||||
try:
|
||||
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
||||
email: str = payload.get("sub")
|
||||
if email is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Could not validate credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
return email
|
||||
except JWTError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Could not validate credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
0
app/db/__init__.py
Normal file
0
app/db/__init__.py
Normal file
3
app/db/base.py
Normal file
3
app/db/base.py
Normal file
@ -0,0 +1,3 @@
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
|
||||
Base = declarative_base()
|
22
app/db/session.py
Normal file
22
app/db/session.py
Normal file
@ -0,0 +1,22 @@
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from pathlib import Path
|
||||
|
||||
DB_DIR = Path("/app/storage/db")
|
||||
DB_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_DIR}/db.sqlite"
|
||||
|
||||
engine = create_engine(
|
||||
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
|
||||
)
|
||||
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
0
app/models/__init__.py
Normal file
0
app/models/__init__.py
Normal file
27
app/models/booking.py
Normal file
27
app/models/booking.py
Normal file
@ -0,0 +1,27 @@
|
||||
from sqlalchemy import Column, Integer, String, DateTime, Text, ForeignKey, Numeric
|
||||
from sqlalchemy.orm import relationship
|
||||
from sqlalchemy.sql import func
|
||||
from app.db.base import Base
|
||||
|
||||
|
||||
class Booking(Base):
|
||||
__tablename__ = "bookings"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
booking_type = Column(String, nullable=False) # flight, hotel, car_rental, activity
|
||||
reference_number = Column(String, unique=True, nullable=False)
|
||||
provider = Column(String, nullable=False)
|
||||
description = Column(Text)
|
||||
start_date = Column(DateTime, nullable=False)
|
||||
end_date = Column(DateTime)
|
||||
total_amount = Column(Numeric(10, 2), nullable=False)
|
||||
currency = Column(String, default="USD")
|
||||
status = Column(String, default="confirmed") # confirmed, cancelled, pending
|
||||
booking_details = Column(Text) # JSON string for flexible booking data
|
||||
user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
||||
trip_id = Column(Integer, ForeignKey("trips.id"))
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
|
||||
|
||||
user = relationship("User", back_populates="bookings")
|
||||
trip = relationship("Trip", back_populates="bookings")
|
21
app/models/destination.py
Normal file
21
app/models/destination.py
Normal file
@ -0,0 +1,21 @@
|
||||
from sqlalchemy import Column, Integer, String, Text, Numeric
|
||||
from sqlalchemy.sql import func
|
||||
from sqlalchemy import DateTime
|
||||
from app.db.base import Base
|
||||
|
||||
|
||||
class Destination(Base):
|
||||
__tablename__ = "destinations"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String, nullable=False, index=True)
|
||||
country = Column(String, nullable=False)
|
||||
city = Column(String, nullable=False)
|
||||
description = Column(Text)
|
||||
latitude = Column(Numeric(10, 8))
|
||||
longitude = Column(Numeric(11, 8))
|
||||
category = Column(String) # city, beach, mountain, cultural, adventure, etc.
|
||||
rating = Column(Numeric(3, 2))
|
||||
image_url = Column(String)
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
|
40
app/models/trip.py
Normal file
40
app/models/trip.py
Normal file
@ -0,0 +1,40 @@
|
||||
from sqlalchemy import Column, Integer, String, DateTime, Text, ForeignKey, Numeric
|
||||
from sqlalchemy.orm import relationship
|
||||
from sqlalchemy.sql import func
|
||||
from app.db.base import Base
|
||||
|
||||
|
||||
class Trip(Base):
|
||||
__tablename__ = "trips"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
title = Column(String, nullable=False)
|
||||
description = Column(Text)
|
||||
start_date = Column(DateTime, nullable=False)
|
||||
end_date = Column(DateTime, nullable=False)
|
||||
budget = Column(Numeric(10, 2))
|
||||
status = Column(String, default="planned") # planned, active, completed, cancelled
|
||||
user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
|
||||
|
||||
user = relationship("User", back_populates="trips")
|
||||
itinerary = relationship("Itinerary", back_populates="trip")
|
||||
bookings = relationship("Booking", back_populates="trip")
|
||||
|
||||
|
||||
class Itinerary(Base):
|
||||
__tablename__ = "itineraries"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
trip_id = Column(Integer, ForeignKey("trips.id"), nullable=False)
|
||||
destination_id = Column(Integer, ForeignKey("destinations.id"), nullable=False)
|
||||
day_number = Column(Integer, nullable=False)
|
||||
activity = Column(String, nullable=False)
|
||||
description = Column(Text)
|
||||
start_time = Column(DateTime)
|
||||
end_time = Column(DateTime)
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
trip = relationship("Trip", back_populates="itinerary")
|
||||
destination = relationship("Destination")
|
20
app/models/user.py
Normal file
20
app/models/user.py
Normal file
@ -0,0 +1,20 @@
|
||||
from sqlalchemy import Column, Integer, String, DateTime, Boolean
|
||||
from sqlalchemy.orm import relationship
|
||||
from sqlalchemy.sql import func
|
||||
from app.db.base import Base
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
email = Column(String, unique=True, index=True, nullable=False)
|
||||
username = Column(String, unique=True, index=True, nullable=False)
|
||||
full_name = Column(String, nullable=False)
|
||||
hashed_password = Column(String, nullable=False)
|
||||
is_active = Column(Boolean, default=True)
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
|
||||
|
||||
trips = relationship("Trip", back_populates="user")
|
||||
bookings = relationship("Booking", back_populates="user")
|
0
app/schemas/__init__.py
Normal file
0
app/schemas/__init__.py
Normal file
46
app/schemas/booking.py
Normal file
46
app/schemas/booking.py
Normal file
@ -0,0 +1,46 @@
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
|
||||
|
||||
class BookingBase(BaseModel):
|
||||
booking_type: str
|
||||
reference_number: str
|
||||
provider: str
|
||||
description: Optional[str] = None
|
||||
start_date: datetime
|
||||
end_date: Optional[datetime] = None
|
||||
total_amount: Decimal
|
||||
currency: str = "USD"
|
||||
status: str = "confirmed"
|
||||
booking_details: Optional[str] = None
|
||||
trip_id: Optional[int] = None
|
||||
|
||||
|
||||
class BookingCreate(BookingBase):
|
||||
pass
|
||||
|
||||
|
||||
class BookingUpdate(BaseModel):
|
||||
booking_type: Optional[str] = None
|
||||
reference_number: Optional[str] = None
|
||||
provider: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
start_date: Optional[datetime] = None
|
||||
end_date: Optional[datetime] = None
|
||||
total_amount: Optional[Decimal] = None
|
||||
currency: Optional[str] = None
|
||||
status: Optional[str] = None
|
||||
booking_details: Optional[str] = None
|
||||
trip_id: Optional[int] = None
|
||||
|
||||
|
||||
class BookingResponse(BookingBase):
|
||||
id: int
|
||||
user_id: int
|
||||
created_at: datetime
|
||||
updated_at: Optional[datetime] = None
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
41
app/schemas/destination.py
Normal file
41
app/schemas/destination.py
Normal file
@ -0,0 +1,41 @@
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
|
||||
|
||||
class DestinationBase(BaseModel):
|
||||
name: str
|
||||
country: str
|
||||
city: str
|
||||
description: Optional[str] = None
|
||||
latitude: Optional[Decimal] = None
|
||||
longitude: Optional[Decimal] = None
|
||||
category: Optional[str] = None
|
||||
rating: Optional[Decimal] = None
|
||||
image_url: Optional[str] = None
|
||||
|
||||
|
||||
class DestinationCreate(DestinationBase):
|
||||
pass
|
||||
|
||||
|
||||
class DestinationUpdate(BaseModel):
|
||||
name: Optional[str] = None
|
||||
country: Optional[str] = None
|
||||
city: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
latitude: Optional[Decimal] = None
|
||||
longitude: Optional[Decimal] = None
|
||||
category: Optional[str] = None
|
||||
rating: Optional[Decimal] = None
|
||||
image_url: Optional[str] = None
|
||||
|
||||
|
||||
class DestinationResponse(DestinationBase):
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: Optional[datetime] = None
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
58
app/schemas/trip.py
Normal file
58
app/schemas/trip.py
Normal file
@ -0,0 +1,58 @@
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
|
||||
|
||||
class TripBase(BaseModel):
|
||||
title: str
|
||||
description: Optional[str] = None
|
||||
start_date: datetime
|
||||
end_date: datetime
|
||||
budget: Optional[Decimal] = None
|
||||
status: str = "planned"
|
||||
|
||||
|
||||
class TripCreate(TripBase):
|
||||
pass
|
||||
|
||||
|
||||
class TripUpdate(BaseModel):
|
||||
title: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
start_date: Optional[datetime] = None
|
||||
end_date: Optional[datetime] = None
|
||||
budget: Optional[Decimal] = None
|
||||
status: Optional[str] = None
|
||||
|
||||
|
||||
class TripResponse(TripBase):
|
||||
id: int
|
||||
user_id: int
|
||||
created_at: datetime
|
||||
updated_at: Optional[datetime] = None
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class ItineraryBase(BaseModel):
|
||||
destination_id: int
|
||||
day_number: int
|
||||
activity: str
|
||||
description: Optional[str] = None
|
||||
start_time: Optional[datetime] = None
|
||||
end_time: Optional[datetime] = None
|
||||
|
||||
|
||||
class ItineraryCreate(ItineraryBase):
|
||||
pass
|
||||
|
||||
|
||||
class ItineraryResponse(ItineraryBase):
|
||||
id: int
|
||||
trip_id: int
|
||||
created_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
44
app/schemas/user.py
Normal file
44
app/schemas/user.py
Normal file
@ -0,0 +1,44 @@
|
||||
from pydantic import BaseModel, EmailStr
|
||||
from typing import Optional
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
class UserBase(BaseModel):
|
||||
email: EmailStr
|
||||
username: str
|
||||
full_name: str
|
||||
|
||||
|
||||
class UserCreate(UserBase):
|
||||
password: str
|
||||
|
||||
|
||||
class UserUpdate(BaseModel):
|
||||
email: Optional[EmailStr] = None
|
||||
username: Optional[str] = None
|
||||
full_name: Optional[str] = None
|
||||
password: Optional[str] = None
|
||||
|
||||
|
||||
class UserResponse(UserBase):
|
||||
id: int
|
||||
is_active: bool
|
||||
created_at: datetime
|
||||
updated_at: Optional[datetime] = None
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class UserLogin(BaseModel):
|
||||
email: EmailStr
|
||||
password: str
|
||||
|
||||
|
||||
class Token(BaseModel):
|
||||
access_token: str
|
||||
token_type: str
|
||||
|
||||
|
||||
class TokenData(BaseModel):
|
||||
email: Optional[str] = None
|
44
main.py
Normal file
44
main.py
Normal file
@ -0,0 +1,44 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from app.api.routes import auth, trips, destinations, bookings
|
||||
from app.db.session import engine
|
||||
from app.db.base import Base
|
||||
|
||||
app = FastAPI(
|
||||
title="Travel App Backend",
|
||||
description="A comprehensive travel planning and booking API",
|
||||
version="1.0.0",
|
||||
openapi_url="/openapi.json",
|
||||
)
|
||||
|
||||
# CORS configuration
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# Create database tables
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
# Include routers
|
||||
app.include_router(auth.router, prefix="/auth", tags=["Authentication"])
|
||||
app.include_router(trips.router, prefix="/trips", tags=["Trips"])
|
||||
app.include_router(destinations.router, prefix="/destinations", tags=["Destinations"])
|
||||
app.include_router(bookings.router, prefix="/bookings", tags=["Bookings"])
|
||||
|
||||
|
||||
@app.get("/")
|
||||
async def root():
|
||||
return {
|
||||
"title": "Travel App Backend",
|
||||
"documentation": "/docs",
|
||||
"health_check": "/health",
|
||||
}
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
async def health_check():
|
||||
return {"status": "healthy", "service": "travel-app-backend"}
|
10
requirements.txt
Normal file
10
requirements.txt
Normal file
@ -0,0 +1,10 @@
|
||||
fastapi==0.104.1
|
||||
uvicorn[standard]==0.24.0
|
||||
sqlalchemy==2.0.23
|
||||
alembic==1.12.1
|
||||
python-jose[cryptography]==3.3.0
|
||||
passlib[bcrypt]==1.7.4
|
||||
python-multipart==0.0.6
|
||||
pydantic==2.5.0
|
||||
pydantic-settings==2.1.0
|
||||
ruff==0.1.6
|
Loading…
x
Reference in New Issue
Block a user