4/main.py
2025-03-20 09:54:31 +01:00

66 lines
2.2 KiB
Python

import uvicorn
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from app.api.v1.routes import router as v1_router
from app.api.core.middleware import activity_tracker
from app.core.config import settings
from app.db.base import Base
from app.db.session import engine
app = FastAPI(
title=settings.PROJECT_NAME,
openapi_url=f"{settings.API_V1_STR}/openapi.json"
)
# Set all CORS enabled origins
if settings.BACKEND_CORS_ORIGINS:
app.add_middleware(
CORSMiddleware,
allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include activity tracker middleware
app.middleware("http")(activity_tracker)
# Include v1 router
app.include_router(v1_router, prefix=settings.API_V1_STR)
# Create database tables
Base.metadata.create_all(bind=engine)
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
```
This `main.py` file sets up the FastAPI application for the `blog_app` project. Here's a breakdown of what it does:
1. Import necessary modules and dependencies.
2. Create an instance of the `FastAPI` app with the project name and OpenAPI URL.
3. Set up CORS middleware to allow cross-origin requests from specified origins.
4. Include the `activity_tracker` middleware from `app.api.core.middleware`.
5. Include the `v1_router` from `app.api.v1.routes` under the `/v1` prefix.
6. Create database tables using SQLAlchemy's `Base.metadata.create_all` method, which connects to the SQLite database `blog_app.db` (assuming the database URL is configured correctly in `app.core.config`).
7. If the script is run directly (not imported as a module), start the Uvicorn server on `0.0.0.0:8000`.
Note that this code assumes the following project structure:
```
app/
api/
v1/
routes.py
core/
middleware.py
core/
config.py
db/
base.py
session.py
main.py
```
You'll need to create these files and directories, and populate them with the necessary code for your application. Additionally, you'll need to install the required dependencies (e.g., `fastapi`, `uvicorn`, `sqlalchemy`) and configure the database URL in `app.core.config`.