如何在FastAPI中从同一应用程序的其他API调用API?

12 浏览
0 Comments

如何在FastAPI中从同一应用程序的其他API调用API?

我正在使用Fastapi制作一个应用程序,具有以下文件夹结构:

main.py是应用程序的入口点

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.api.v1 import lines, upload
from app.core.config import settings
app = FastAPI(
    title=settings.PROJECT_NAME,
    version=0.1,
    openapi_url=f'{settings.API_V1_STR}/openapi.json',
    root_path=settings.ROOT_PATH
)
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.BACKEND_CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
app.include_router(upload.router, prefix=settings.API_V1_STR)
app.include_router(lines.router, prefix=settings.API_V1_STR)

lines.py中,我有两个GET端点:

  • /one-random-line --> 从.txt文件返回一行随机内容
  • /one-random-line-backwards --> 应返回/one-random-line的输出的反转字符串

由于第二个GET端点的输出应该是第一个GET端点输出的字符串的反转,我尝试按照这里所提到的步骤进行操作

代码如下:

import random
from fastapi import APIRouter, Request
from starlette.responses import RedirectResponse
router = APIRouter(
    prefix="/get-info",
    tags=["Get Information"],
    responses={
        200: {'description': 'Success'},
        400: {'description': 'Bad Request'},
        403: {'description': 'Forbidden'},
        500: {'description': 'Internal Server Error'}
    }
)
@router.get('/one-random-line')
def get_one_random_line(request: Request):
    lines = open('netflix_list.txt').read().splitlines()
    if request.headers.get('accept') in ['application/json', 'application/xml']:
        random_line = random.choice(lines)
    else:
        random_line = 'This is an example'
    return {'line': random_line}
@router.get('/one-random-line-backwards')
def get_one_random_line_backwards():
    url = router.url_path_for('get_one_random_line')
    response = RedirectResponse(url=url)
    return {'message': response[::-1]}

当我这样做时,我会得到以下错误:

TypeError: 'RedirectResponse' object is not subscriptable

当我将第二个GET端点的return更改为return {'message': response}时,我会得到以下输出:

enter image description here

我犯了什么错误?

示例:

如果/one-random-line端点的输出为'Maverick',那么/one-random-line-backwards的输出应为'kcirevam'。

0