python 如何使用FastAPI/Starlette在RedirectResponse中添加正文内容?

62lalag4  于 2022-11-21  发布在  Python
关注(0)|答案(1)|浏览(240)

我想在/check_base终结点内使用音频文件。但是,我无法在RedirectResponse的主体中发送该文件。/check终结点返回RedirectResponse,它只接受URL参数。请帮助我解决此问题。
下面是我的代码:

@router.post("/check")
async def check(
    request: Request
):
   file = StarletteUploadFile(filename="/home/hello.wav")
   redirect_url = app.url_path_for("check_base", **{'audio':file)

   response = RedirectResponse(url=redirect_url)
   return response

@router.post("/check_base")
async def check_base(
    request: Request,
    audio: UploadFile = File(...)
):
rxztt3cl

rxztt3cl1#

redirection in the HTTP protocol基本上是一个头文件,即Location响应头文件,指示页面要重定向到的URL。也就是说,它并不阻止在响应中提供主体。由于FastAPI/Starlette的RedirectResponse没有提供相关的content参数,该参数允许您传递主体,您可以使用3xx直接返回自定义Response(redirection)状态码和Location信头,其中包含要重新导向的URL。如果您要重新导向的要求重复使用方法(如POST)和原始请求的主体,那么就可以使用307 Temporary Redirect状态响应码(有关Starlette实现的所有状态码都可以在这里找到)。

工作示例:

应用程序.py

from fastapi import FastAPI, Request, Response, Form, status
from fastapi.templating import Jinja2Templates

app = FastAPI()
templates = Jinja2Templates(directory='templates')
 
@app.post('/submitFinal')
def final(msg: str = Form(...)):
    return f'You reached your destination. The msg is {msg}'
    
@app.post('/submit')
def redirect(msg: str = Form(...)):
    headers = {'Location': '/submitFinal'}
    return Response(content=msg, headers=headers, status_code=status.HTTP_307_TEMPORARY_REDIRECT)

@app.get('/')
def index(request: Request):
    return templates.TemplateResponse('index.html', {'request': request})

模板/索引.html

<!DOCTYPE html>
<html>
   <head>
      <script>
         document.addEventListener('DOMContentLoaded', (event) => {
            document.getElementById("myForm").addEventListener("submit", function (e) {
              e.preventDefault() // Cancel the default action
              var formElement = document.getElementById('myForm');
              var data = new FormData(formElement);
              fetch('/submit', {
                    method: 'POST',
                    body: data
                 })
                 .then(resp => resp.text()) // or, resp.json(), etc.
                 .then(data => {
                    document.getElementById("responseArea").innerHTML = data;
                 })
                 .catch(error => {
                    console.error(error);
                 });
            });
         });
      </script>
   </head>
   <body>
      <h1>Send a message</h1>
      <form id="myForm">
         Message : <input type="text" name="msg" value="foo">
         <input class="submit" type="submit" value="Submit">
      </form>
      <div id="responseArea"></div>
   </body>
</html>

相关问题