使用 python 使用 Fast api 将数据插入数据库
Insert data into database using Fast api using python
我是 FastAPI 的新手,我正在使用 FastAPIPOST 方法将数据插入我的 SQL 数据库。我创建了一组示例代码来创建模式,并使用以下示例代码将单个数据插入到 MY SQL table 中。
参考 link:https://codingnomads.co/blog/python-fastapi-tutorial
from fastapi import FastAPI, Depends
from pydantic import BaseModel
from typing import Optional, List
from sqlalchemy import create_engine
from sqlalchemy.orm import declarative_base, sessionmaker, Session
from sqlalchemy import Boolean, Column, Float, String, Integer
app = FastAPI()
# SqlAlchemy Setup
SQLALCHEMY_DATABASE_URL = 'sqlite+pysqlite:///./db.sqlite3:'
engine = create_engine(SQLALCHEMY_DATABASE_URL, echo=True, future=True)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
# A SQLAlchemny ORM Place
class DBPlace(Base):
__tablename__ = 'places'
id = Column(Integer, primary_key=True, index=True)
name = Column(String(50))
description = Column(String, nullable=True)
coffee = Column(Boolean)
wifi = Column(Boolean)
food = Column(Boolean)
lat = Column(Float)
lng = Column(Float)
Base.metadata.create_all(bind=engine)
# A Pydantic Place
class Place(BaseModel):
name: str
description: Optional[str] = None
coffee: bool
wifi: bool
food: bool
lat: float
lng: float
class Config:
orm_mode = True
# Methods for interacting with the database
def get_place(db: Session, place_id: int):
return db.query(DBPlace).where(DBPlace.id == place_id).first()
def get_places(db: Session):
return db.query(DBPlace).all()
def create_place(db: Session, place: Place):
db_place = DBPlace(**place.dict())
db.add(db_place)
db.commit()
db.refresh(db_place)
return db_place
# Routes for interacting with the API
@app.post('/places/', response_model=Place)
def create_places_view(place: Place, db: Session = Depends(get_db)):
db_place = create_place(db, place)
return db_place
@app.get('/places/', response_model=List[Place])
def get_places_view(db: Session = Depends(get_db)):
return get_places(db)
@app.get('/place/{place_id}')
def get_place_view(place_id: int, db: Session = Depends(get_db)):
return get_place(db, place_id)
@app.get('/')
async def root():
return {'message': 'Hello World!'}
但我需要解析 create_places_view 请求中的数组列表并一次插入多个值。那么如何在 Fast API 中实现这一点。有 pointers/help 吗?谢谢
示例:
[{name: str
description: Optional[str] = None
coffee: bool
wifi: bool
food: bool
lat: float
lng: float },
{name: str
description: Optional[str] = None
coffee: bool
wifi: bool
food: bool
lat: float
lng: float }]
我已经循环创建用户的值。在 dict.
列表中发送 post 请求时
# Fast API to create/insert a new user
@app.post('/create_place_view/', responses={404: {"model": Message}})
async def create_place(user: List[Place], db: Session = Depends(get_db)):
if not user:
return JSONResponse(status_code=404, content={"message": "Place details not found"})
else:
places_list = []
for places in place:
db_place = create_places(db, places)
place_json = places.dict()
places_list.append(places_json)
return JSONResponse(content=places_list)
我是 FastAPI 的新手,我正在使用 FastAPIPOST 方法将数据插入我的 SQL 数据库。我创建了一组示例代码来创建模式,并使用以下示例代码将单个数据插入到 MY SQL table 中。
参考 link:https://codingnomads.co/blog/python-fastapi-tutorial
from fastapi import FastAPI, Depends
from pydantic import BaseModel
from typing import Optional, List
from sqlalchemy import create_engine
from sqlalchemy.orm import declarative_base, sessionmaker, Session
from sqlalchemy import Boolean, Column, Float, String, Integer
app = FastAPI()
# SqlAlchemy Setup
SQLALCHEMY_DATABASE_URL = 'sqlite+pysqlite:///./db.sqlite3:'
engine = create_engine(SQLALCHEMY_DATABASE_URL, echo=True, future=True)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
# A SQLAlchemny ORM Place
class DBPlace(Base):
__tablename__ = 'places'
id = Column(Integer, primary_key=True, index=True)
name = Column(String(50))
description = Column(String, nullable=True)
coffee = Column(Boolean)
wifi = Column(Boolean)
food = Column(Boolean)
lat = Column(Float)
lng = Column(Float)
Base.metadata.create_all(bind=engine)
# A Pydantic Place
class Place(BaseModel):
name: str
description: Optional[str] = None
coffee: bool
wifi: bool
food: bool
lat: float
lng: float
class Config:
orm_mode = True
# Methods for interacting with the database
def get_place(db: Session, place_id: int):
return db.query(DBPlace).where(DBPlace.id == place_id).first()
def get_places(db: Session):
return db.query(DBPlace).all()
def create_place(db: Session, place: Place):
db_place = DBPlace(**place.dict())
db.add(db_place)
db.commit()
db.refresh(db_place)
return db_place
# Routes for interacting with the API
@app.post('/places/', response_model=Place)
def create_places_view(place: Place, db: Session = Depends(get_db)):
db_place = create_place(db, place)
return db_place
@app.get('/places/', response_model=List[Place])
def get_places_view(db: Session = Depends(get_db)):
return get_places(db)
@app.get('/place/{place_id}')
def get_place_view(place_id: int, db: Session = Depends(get_db)):
return get_place(db, place_id)
@app.get('/')
async def root():
return {'message': 'Hello World!'}
但我需要解析 create_places_view 请求中的数组列表并一次插入多个值。那么如何在 Fast API 中实现这一点。有 pointers/help 吗?谢谢
示例:
[{name: str description: Optional[str] = None coffee: bool wifi: bool food: bool lat: float lng: float }, {name: str description: Optional[str] = None coffee: bool wifi: bool food: bool lat: float lng: float }]
我已经循环创建用户的值。在 dict.
列表中发送 post 请求时# Fast API to create/insert a new user
@app.post('/create_place_view/', responses={404: {"model": Message}})
async def create_place(user: List[Place], db: Session = Depends(get_db)):
if not user:
return JSONResponse(status_code=404, content={"message": "Place details not found"})
else:
places_list = []
for places in place:
db_place = create_places(db, places)
place_json = places.dict()
places_list.append(places_json)
return JSONResponse(content=places_list)