Update code in endpoints/pen.post.py
This commit is contained in:
parent
bb0c35c7d2
commit
cf370d7df3
81
endpoints/pen.post.py
Normal file
81
endpoints/pen.post.py
Normal file
@ -0,0 +1,81 @@
|
||||
Sure, here's an example of a FastAPI endpoint that saves data to a database using SQLAlchemy and Pydantic:
|
||||
|
||||
```python
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import Column, Integer, String
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
# SQLAlchemy setup
|
||||
Base = declarative_base()
|
||||
engine = create_engine('sqlite:///database.db', echo=True)
|
||||
Session = sessionmaker(bind=engine)
|
||||
|
||||
# SQLAlchemy model
|
||||
class Pen(Base):
|
||||
__tablename__ = 'pens'
|
||||
|
||||
id = Column(Integer, primary_key=True)
|
||||
name = Column(String)
|
||||
color = Column(String)
|
||||
brand = Column(String)
|
||||
|
||||
def __repr__(self):
|
||||
return f"Pen(id={self.id}, name='{self.name}', color='{self.color}', brand='{self.brand}')"
|
||||
|
||||
Base.metadata.create_all(engine)
|
||||
|
||||
# Pydantic model
|
||||
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:
|
||||
pen_obj = Pen(name=pen.name, color=pen.color, brand=pen.brand)
|
||||
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:
|
||||
session.close()
|
||||
```
|
||||
|
||||
Here's a breakdown of the code:
|
||||
|
||||
1. We import the necessary modules from FastAPI, Pydantic, and SQLAlchemy.
|
||||
2. We set up SQLAlchemy by creating a declarative base, engine, and session maker.
|
||||
3. We define the `Pen` model using SQLAlchemy's `declarative_base` and `Column` classes.
|
||||
4. We create a Pydantic model `PenSchema` that will be used for data validation and serialization/deserialization.
|
||||
5. We define the `/pen` endpoint using the `@app.post` decorator from FastAPI.
|
||||
6. Inside the `save_pen` function, we create a new SQLAlchemy session and try to save the pen data to the database.
|
||||
7. If the operation is successful, we commit the changes and return a success message.
|
||||
8. If an exception occurs, we roll back the changes and raise an `HTTPException` with a 500 status code and the error message.
|
||||
9. Finally, we close the session in the `finally` block.
|
||||
|
||||
To use this endpoint, you can send a POST request to `/pen` with a JSON payload containing the pen data, like this:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "Pilot G2",
|
||||
"color": "Blue",
|
||||
"brand": "Pilot"
|
||||
}
|
||||
```
|
||||
|
||||
The endpoint will validate the data using the `PenSchema` model, create a new `Pen` instance, and save it to the database.
|
||||
|
||||
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