Update code in endpoints/pen.post.py
This commit is contained in:
parent
cf370d7df3
commit
aa6082d607
@ -12,70 +12,70 @@ app = FastAPI()
|
|||||||
|
|
||||||
# SQLAlchemy setup
|
# SQLAlchemy setup
|
||||||
Base = declarative_base()
|
Base = declarative_base()
|
||||||
engine = create_engine('sqlite:///database.db', echo=True)
|
engine = create_engine('sqlite:///database.db', connect_args={'check_same_thread': False})
|
||||||
Session = sessionmaker(bind=engine)
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||||
|
|
||||||
|
# Pydantic model (schema)
|
||||||
|
class PenSchema(BaseModel):
|
||||||
|
name: str
|
||||||
|
color: str
|
||||||
|
price: float
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
orm_mode = True
|
||||||
|
|
||||||
# SQLAlchemy model
|
# SQLAlchemy model
|
||||||
class Pen(Base):
|
class Pen(Base):
|
||||||
__tablename__ = 'pens'
|
__tablename__ = 'pens'
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
name = Column(String)
|
name = Column(String)
|
||||||
color = Column(String)
|
color = Column(String)
|
||||||
brand = Column(String)
|
price = Column(Integer)
|
||||||
|
|
||||||
def __repr__(self):
|
Base.metadata.create_all(bind=engine)
|
||||||
return f"Pen(id={self.id}, name='{self.name}', color='{self.color}', brand='{self.brand}')"
|
|
||||||
|
|
||||||
Base.metadata.create_all(engine)
|
# Dependency
|
||||||
|
def get_db():
|
||||||
# Pydantic model
|
db = SessionLocal()
|
||||||
class PenSchema(BaseModel):
|
|
||||||
name: str
|
|
||||||
color: str
|
|
||||||
brand: str
|
|
||||||
|
|
||||||
class Config:
|
|
||||||
orm_mode = True
|
|
||||||
|
|
||||||
# Endpoint to save a pen to the database
|
|
||||||
@app.post('/pen')
|
|
||||||
def save_pen(pen: PenSchema):
|
|
||||||
session = Session()
|
|
||||||
try:
|
try:
|
||||||
pen_obj = Pen(name=pen.name, color=pen.color, brand=pen.brand)
|
yield db
|
||||||
session.add(pen_obj)
|
|
||||||
session.commit()
|
|
||||||
return {"message": "Pen saved successfully"}
|
|
||||||
except Exception as e:
|
|
||||||
session.rollback()
|
|
||||||
raise HTTPException(status_code=500, detail=str(e))
|
|
||||||
finally:
|
finally:
|
||||||
session.close()
|
db.close()
|
||||||
|
|
||||||
|
@app.post('/pen', status_code=201)
|
||||||
|
def create_pen(pen: PenSchema, db=get_db()):
|
||||||
|
new_pen = Pen(name=pen.name, color=pen.color, price=pen.price)
|
||||||
|
db.add(new_pen)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(new_pen)
|
||||||
|
return new_pen
|
||||||
```
|
```
|
||||||
|
|
||||||
Here's a breakdown of the code:
|
Here's a breakdown of the code:
|
||||||
|
|
||||||
1. We import the necessary modules from FastAPI, Pydantic, and SQLAlchemy.
|
1. We import the necessary modules and create a FastAPI instance.
|
||||||
2. We set up SQLAlchemy by creating a declarative base, engine, and session maker.
|
2. We set up SQLAlchemy with a SQLite database and define a base class for our models.
|
||||||
3. We define the `Pen` model using SQLAlchemy's `declarative_base` and `Column` classes.
|
3. We define a Pydantic model (`PenSchema`) to validate and parse the incoming data.
|
||||||
4. We create a Pydantic model `PenSchema` that will be used for data validation and serialization/deserialization.
|
4. We define a SQLAlchemy model (`Pen`) that maps to the `pens` table in the database.
|
||||||
5. We define the `/pen` endpoint using the `@app.post` decorator from FastAPI.
|
5. We create the `pens` table in the database using `Base.metadata.create_all(bind=engine)`.
|
||||||
6. Inside the `save_pen` function, we create a new SQLAlchemy session and try to save the pen data to the database.
|
6. We define a dependency function `get_db()` that creates a new database session for each request and closes it after the request is processed.
|
||||||
7. If the operation is successful, we commit the changes and return a success message.
|
7. We define the `/pen` endpoint with the `POST` method and the `status_code=201` (Created) response.
|
||||||
8. If an exception occurs, we roll back the changes and raise an `HTTPException` with a 500 status code and the error message.
|
8. Inside the endpoint function, we create a new `Pen` instance using the data from the `PenSchema` model.
|
||||||
9. Finally, we close the session in the `finally` block.
|
9. We add the new `Pen` instance to the database session, commit the changes, and refresh the instance to get the generated ID.
|
||||||
|
10. Finally, we return the new `Pen` instance.
|
||||||
|
|
||||||
To use this endpoint, you can send a POST request to `/pen` with a JSON payload containing the pen data, like this:
|
To use this endpoint, you can send a POST request to `/pen` with a JSON payload containing the pen details, like this:
|
||||||
|
|
||||||
|
```
|
||||||
|
POST /pen
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
{
|
||||||
"name": "Pilot G2",
|
"name": "Pilot FriXion",
|
||||||
"color": "Blue",
|
"color": "Black",
|
||||||
"brand": "Pilot"
|
"price": 2.99
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
The endpoint will validate the data using the `PenSchema` model, create a new `Pen` instance, and save it to the database.
|
The endpoint will create a new pen in the database and return the created pen object with the generated ID.
|
||||||
|
|
||||||
Note that you'll need to have SQLAlchemy and a compatible database driver installed for this code to work. In this example, we're using SQLite, but you can easily switch to a different database by modifying the engine URL.
|
|
Loading…
x
Reference in New Issue
Block a user