fastapi:将 sqlalchemy 数据库模型映射到 pydantic geojson 功能

dlq*_*map 10 python sqlalchemy geojson pydantic fastapi

我刚刚开始使用 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)
Run Code Online (Sandbox Code Playgroud)

使用的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]
Run Code Online (Sandbox Code Playgroud)

期望的输出:

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

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)
Run Code Online (Sandbox Code Playgroud)

我仍然试图弄清楚如何将nametype_id列从数据库模型映射到PoiProperties对象中PoiFeature

fch*_*cel 4

您想要返回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))
Run Code Online (Sandbox Code Playgroud)

或者只是在不同的模式类中使用 orm 模式