blog_app_igblf/main.py

54 lines
1.8 KiB
Python

Here's a `main.py` file for a FastAPI backend named 'blog_app' with necessary imports and middleware, including SQLite and SQLAlchemy support:
import os
from typing import List
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session
from sqlalchemy.ext.declarative import declarative_base
SQLALCHEMY_DATABASE_URL = "sqlite:///./blog_app.db"
engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
app = FastAPI()
origins = [
"http://localhost",
"http://localhost:3000",
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
from models import Base
Base.metadata.create_all(bind=engine)
from routers import blog, user
app.include_router(blog.router)
app.include_router(user.router)
@app.get("/")
def root():
return {"message": "Welcome to the Blog App!"}
This `main.py` file sets up the necessary components for a FastAPI backend with SQLite and SQLAlchemy support. Here's a breakdown of what's included:
7. Creates database tables if they don't exist by calling `Base.metadata.create_all(bind=engine)`.
8. Imports routers for blog and user functionality (assuming you have separate router files).
10. Defines a root path (`/`) that returns a welcome message.
Note that this `main.py` file assumes you have separate files for models (`models.py`) and routers (`routers/blog.py` and `routers/user.py`). You'll need to create those files and define your models and routes accordingly.