53 lines
1.4 KiB
Python
53 lines
1.4 KiB
Python
```python
|
|
from fastapi import FastAPI
|
|
from starlette.middleware.cors import CORSMiddleware
|
|
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.ext.declarative import declarative_base
|
|
from sqlalchemy.orm import sessionmaker
|
|
|
|
app = FastAPI()
|
|
|
|
origins = [
|
|
"http://localhost",
|
|
"http://localhost:8000",
|
|
]
|
|
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=origins,
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
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()
|
|
|
|
from . import models, routes
|
|
|
|
app.include_router(routes.router)
|
|
|
|
@app.get("/")
|
|
async def root():
|
|
return {"message": "Welcome to the Blog App!"}
|
|
```
|
|
|
|
|
|
1. Imports necessary FastAPI, middleware, and SQLAlchemy modules.
|
|
2. Creates a FastAPI app instance.
|
|
3. Configures CORS middleware to allow cross-origin requests from specified origins.
|
|
4. Sets up the SQLite database connection using SQLAlchemy.
|
|
5. Imports models and routes after the database configuration to avoid circular imports.
|
|
6. Includes the routes from the `routes` module.
|
|
|
|
|
|
You can run this FastAPI app using the `uvicorn` command:
|
|
|
|
```bash
|
|
uvicorn main:app --reload
|
|
```
|
|
|
|
This will start the development server and automatically reload it when you make changes to the code. |