我正在尝试创建一个音频服务器,我可以在其中上传各种音频文件,我有一个要求,我只能创建一个用于创建的端点,我想出了这个,但它确实显示了输入数据的请求表单。
class AudioType(str, Enum):
Song = "Song"
Podcast = "Podcast"
Audiobook = "Audiobook"
@app.post("/{audio_type}", status_code=status.HTTP_200_OK)
def audio(audio_type: AudioType):
if audio_type == AudioType.Song:
def create_song(request: schemas.Song, db: Session = Depends(database.get_db)):
new_song = models.Song(name=request.name, duration=request.duration, uploadTime=request.uploadTime)
db.add(new_song)
db.commit()
db.refresh(new_song)
return new_song
elif audio_type == AudioType.Podcast:
def create_podcast(request: schemas.Podcast, db: Session = Depends(database.get_db)):
new_podcast = models.Podcast(name=request.name, duration=request.duration, uploadTime=request.uploadTime, host=request.host)
db.add(new_podcast)
db.commit()
db.refresh(new_podcast)
return new_podcast
elif audio_type == AudioType.Audiobook:
def create_audiobook(request: schemas.Audiobook, db: Session = Depends(database.get_db)):
new_audiobook = models.Audiobook(titile=request.title, author=request.author, narrator=request.narrator, duration=request.duration, uploadTime=request.uploadTime)
db.add(new_audiobook)
db.commit()
db.refresh(new_audiobook)
return new_audiobook
答案 0 :(得分:1)
您的方法不接受 request
对象,而只接受 audio_type
。
此外,根据我从您的代码中了解到的情况,您可能有多个请求正文(schemas
,如您所指)
您有两种选择:
您需要按如下方式声明端点:
from typing import Union
@app.post("/{audio_type}", status_code=status.HTTP_200_OK)
def audio(
request: Union[schemas.Song, schemas.Podcast,
schemas.Audiobook], audio_type: AudioType
):
... Your method ...
但是 fastapi 的 auto swagger 不会提供模式示例,您必须手动提供示例,(这可能也可能不可能,我真的不知道也没有尝试过:/)>
或者您可以拥有一个可以接受所有内容作为 Optional
和 audio_type
参数的架构:
from typing import Optional
class EndpointSchema(BaseModel):
audio_type: AudioType
song: Optional[schemas.Song]
podcast: Optional[schemas.Podcast]
audiobook: Optional[schemas.Audiobook]
@app.post("/audio", status_code=status.HTTP_200_OK)
def audio(request_body: EndpointSchema):
if request_body.audio_type == AudioType.Song:
... Continue with your request processing ...
最后,非常重要:您声明了之后不会调用的内部方法(create_song
等),因此您的代码将不执行任何操作。您不需要这样做,直接在 if, elif ...
块内使用您想要创建歌曲、播客或有声读物的代码!