[英]Creating endpoints inside an endpoint in fastapi
假设有一个音频服务器,您可以上传歌曲、播客或有声读物。 所以在创建端点中我创建了 4 个端点,所以如果 audio_type 是一首歌,我设置了一个条件,返回该类型的所有音频,但不幸的是这返回 null
@app.get('/audio/{audio_type}')
def show_all(audio_type):
if audio_type == "Songs":
@app.get("audio/song")
def all(db: Session = Depends(database.get_db)):
songs = db.query(models.Song).all()
print("songs = ", songs)
return songs
elif audio_type == "podcast":
@app.get('audio/podcast')
def all(db: Session = Depends(database.get_db)):
podcast = db.query(models.Podcast).all()
return podcast
elif audio_type == "audiobook":
@app.get('audio/audiobook')
def all(db: Session = Depends(database.get_db)):
audiobook = db.query(models.Audiobook).all()
return audiobook
else:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f' {audio_type} - audio type is not valid')
您的实现正在破坏 API 的目的。 对于这样的实现,请尝试将该值作为参数传递给您的 API,并在此基础上对流进行分叉。
def all(db: Session = Depends(database.get_db), audio_type):
if audio_type == "Songs":
songs = db.query(models.Song).all()
print("songs = ", songs)
return songs
elif audio_type == "podcast":
podcast = db.query(models.Podcast).all()
return podcast
elif audio_type == "audiobook":
audiobook = db.query(models.Audiobook).all()
return audiobook
else:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f' {audio_type} - audio type is not valid')
@app.get('/audio')
def show_all(audio_type: str):
return all(Depends(database.get_db), audio_type):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.