使用Python使用Fast api将数据插入数据库
我是 FastAPI 的新手,我正在使用 Fast API POST 方法将数据插入 MY SQL 数据库。我创建了一组示例代码来创建架构,并使用以下示例代码将单个数据插入 MY SQL 表中。
参考链接: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 中实现这一点呢?有任何指示/帮助吗?谢谢
示例:
<前><代码> [{名称:str 描述:可选[str] =无 咖啡:布尔 无线网络:布尔 食物:布尔 纬度:浮动 lng: 浮动 }, {名称:str 描述:可选[str] =无 咖啡:布尔 无线网络:布尔 食物:布尔 纬度:浮动 lng:浮动}]
I am new to FastAPI and I'm working on inserting data into MY SQL database using the Fast API POST method. I have created a set of sample codes to create a schema and inserted the single data into the MY SQL table using the below sample code.
Ref 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!'}
But I need to parse a list of arrays in the request to create_places_view and insert multiple values at once. so how to achieve this in Fast API. Any pointers/help? Thanks
Example:
[{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 }]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我已循环创建用户的值。在dict列表中发送post请求时。
I have looped the value to create user. While sending the post request in the list of dict.