fastapi:将sqlalchemy数据库模型映射到pydanticgeojson特性



我刚开始玩FastAPI、SQLAlchemy、Pydantic,我正在尝试构建一个简单的API端点,以返回postgis表中的行作为geojson功能集合。

这是我的sqlalchemy型号:

class Poi(Base):
__tablename__ = 'poi'
id = Column(Integer, primary_key=True)
name = Column(Text, nullable=False)
type_id = Column(Integer)
geometry = Column(Geometry('POINT', 4326, from_text='ST_GeomFromEWKT'),
nullable=False)

使用geojson_pydantic,相关的pydantic模型为:

from geojson_pydantic.features import Feature, FeatureCollection
from geojson_pydantic.geometries import Point
from typing import List
class PoiProperties(BaseModel):
name: str
type_id: int
class PoiFeature(Feature):
id: int
geometry: Point
properties: PoiProperties
class PoiCollection(FeatureCollection):
features: List[PoiFeature]

期望输出:

理想情况下,我希望能够检索并返回数据库记录,如下所示:

def get_pois(db: Session, skip: int = 0, limit: int = 100):
return db.query(Poi).offset(skip).limit(limit).all()

@app.get("/geojson", response_model=PoiCollection)
def read_geojson(skip: int = 0,
limit: int = 100,
db: Session = Depends(get_db)):
return get_pois(db, skip=skip, limit=limit)

尽管如此,我还是试图弄清楚如何将数据库模型中的nametype_id列映射到PoiFeature对象中的PoiProperties

您希望返回PoiCollection模式(response_model=schemas.PoiCollection),但不需要任何格式即可直接返回数据库响应。因此,您必须将crud响应转换为模式响应。

# Different function for translate db response to Pydantic response according to your different schema
def make_response_poi_properties(poi):
return PoiFeature(name=poi.name, type_id=poi.type_id) 
def make_response_poi_feature(poi):
return PoiFeature(id=poi.id, geometry=poi.geometry,properties=make_response_poi_properties(poi)) 
def make_response_poi_collection(pois):
response = []
for poi in pois:
response.append(make_response_poi_feature(poi)
return response
@app.get("/geojson", response_model=PoiCollection)
def read_geojson(skip: int = 0,
limit: int = 100,
db: Session = Depends(get_db)):

# Call function for translate db data to pydantic data according to your response_model
return make_response_poi_collection(get_pois(db, skip=skip, limit=limit))

或者简单地在不同的模式类中使用orm模式

最新更新