首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在fastapi中的端点内创建端点

在fastapi中的端点内创建端点
EN

Stack Overflow用户
提问于 2021-03-23 00:08:05
回答 1查看 46关注 0票数 0

假设有一个音频服务器,您可以上传歌曲、播客或有声读物。在create endpoint中,我已经创建了4个endpoint,所以我设置了一个条件,如果audio_type是一首歌,则返回该类型的所有音频,但不幸的是,这将返回null

代码语言:javascript
复制
@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')
EN

回答 1

Stack Overflow用户

发布于 2021-03-23 00:28:53

您的实现违背了API的目的。对于这样的实现,尝试将该值作为参数传递给您的API,并在此基础上将流分叉。

代码语言:javascript
复制
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):
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66749744

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档