Update code in endpoints/countries.post.py

This commit is contained in:
Backend IM Bot 2025-03-25 12:04:41 +01:00
parent 6d5f43843a
commit 744b95c1eb

View File

@ -0,0 +1,60 @@
Sure, here's an example of a FastAPI endpoint that saves countries to a database using SQLAlchemy and Pydantic schemas:
```python
from typing import List
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from . import models, schemas
from .database import SessionLocal, engine
router = APIRouter()
# Create the database tables
models.Base.metadata.create_all(bind=engine)
# Dependency for getting a database session
@router.post("/countries", response_model=List[schemas.Country])
def create_countries(countries: List[schemas.CountryCreate], db: Session = Depends(get_db)):
db_countries = []
for country_data in countries:
db_country = models.Country(name=country_data.name, capital=country_data.capital)
db.add(db_country)
db.commit()
db.refresh(db_country)
db_countries.append(db_country)
return db_countries
```
Here's what's happening:
1. We import the necessary modules and create a router instance.
2. We create the database tables using `models.Base.metadata.create_all(bind=engine)`.
3. We define a dependency function `get_db()` that creates a new database session and yields it for use in the endpoint function. The session is closed after the function returns.
4. We define the endpoint function `create_countries()` that takes a list of `CountryCreate` Pydantic models as input and returns a list of `Country` Pydantic models.
5. Inside the endpoint function, we iterate over the input `countries` list and create a new `Country` model instance for each country data.
6. We add the new `Country` instance to the database session using `db.add(db_country)`.
7. We commit the changes to the database using `db.commit()`.
8. We refresh the `db_country` instance with the data from the database using `db.refresh(db_country)`.
9. We append the refreshed `db_country` instance to the `db_countries` list.
10. Finally, we return the `db_countries` list.
Here are the SQLAlchemy model and Pydantic schemas used in the example:
```python
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import declarative_base
from pydantic import BaseModel
from app.api.models.countries_model import *
from app.api.schemas.countries_schema import *
from app.api.dependencies.countries_deps import *
Base = declarative_base()
class Config:
orm_mode = True
```
In this example, we define an SQLAlchemy model `Country` with columns for `id`, `name`, and `capital`. We also define two Pydantic models: `CountryCreate` for creating new countries, and `Country` for representing existing countries in the database.
Note that the `Country` Pydantic model has an `orm_mode` configuration set to `True`, which allows Pydantic to automatically convert SQLAlchemy model instances to Pydantic model instances and vice versa.