FastAPI 的 RedirectResponse 在 Swagger UI 中无法按预期工作

2024-03-17

我有一个带下载端点的 FastAPI 应用程序。此下载端点的作用是使用BlobServiceClient(对于 Azure Blob 存储)生成请求中指定的文件的令牌和 Blob URL。我想要做的是将用户重定向到该 URL。这是下载点的代码片段(我注释掉了一些内容,因为我不允许显示代码)。

@router.get("..path", tags=["some tags"], summary=..., responses={404: {"model": ...}, 403: {"model": ...}, 307: {"model": ...}}, response_model_exclude_none=True)
async def download_file(
        # there's a depends on an API key
        blob_path: str = Query(
            ...
        )):
credential = ClientSecretCredential(...)  //secrets
blob_service_client = BlobServiceClient(f"https://{storage_account}.blob.core.windows.net", credential=credential)
user_delegation_key = blob_service_client.get_user_delegation_key(key_start_time=datetime.utcnow(),key_expiry_time=datetime.utcnow() + timedelta(minutes=30))
    
token = generate_blob_sas(account_name=...,                                 
                          container_name=...,                                 
                          blob_name=blob_path,
                          user_delegation_key=user_delegation_key,
                          permission=BlobSasPermissions(read=True),
                          expiry=datetime.utcnow() + timedelta(minutes=30))
    
blob_url = f'https://{storage_account}.blob.core.windows.net/{container_name}/{blob_path}?{token}' 
print(blob_url)  
response = RedirectResponse(blob_url) 
return response

我期望的是执行查询,返回响应后,下载将在后台或单独的选项卡中开始。相反,我得到的是不同的响应,正如您在 Swagger 中看到的那样:

我还查看了“网络”选项卡,看看该请求发生了什么:

看起来有一个OPTIONS请求,并且我假设我正在收到对该请求的响应。不确定 Swagger 是否是这样处理请求的。知道如何/为什么会发生这种情况以及如何解决它吗?谢谢你!


首先,HTTP 选项 https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS, in CORS https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS, is a 飞行前请求 https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request在实际请求之前由浏览器自动发出的,而不是返回File回复。它请求给定服务器允许的通信选项,并且服务器以Access-Control-Allow-Methods https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods标头包括一组允许的方法(例如,Access-Control-Allow-Methods: OPTIONS, GET, HEAD, POST, DELETE)。可以选择使用以下命令缓存在同一 URL 中创建的请求的预检响应Access-Control-Max-Ageheader,从而允许服务器限制预检请求的数量。该标头的值以秒为单位表示;因此,例如,允许缓存 10 分钟看起来像Access-Control-Max-Age: 600.

至于RedirectResponse https://fastapi.tiangolo.com/es/advanced/custom-response/#redirectresponse, Swagger UI 始终遵循重定向响应 https://github.com/swagger-api/swagger-ui/issues/1569#issuecomment-390877095. In a fetch https://developer.mozilla.org/en-US/docs/Web/API/fetch请求,例如redirect https://developer.mozilla.org/en-US/docs/Web/API/fetch#syntax参数将设置为follow,表明redirect应该遵循。这意味着 Swagger UI 遵循重定向并等待完全接收响应,然后再为您提供Download file链接(如您上面提供的屏幕截图所示)允许您下载该文件。这也是为什么您无法在后台或新选项卡中看到下载开始的原因。正如上面链接的 github 帖子中提到的,无法更改该行为,这可以让您以不同的方式处理它,类似于中演示的方法这个答案 https://stackoverflow.com/a/75188418/17865804.

您可以通过在浏览器地址栏中键入 API 端点的 URL 来直接测试它(因为它是一个GET端点,您可以这样做,因为当您在浏览器的地址栏中键入 URL 时,它会执行GET请求),或创建您自己的自定义Template https://fastapi.tiangolo.com/advanced/templates/(或使用HTMLResponse https://fastapi.tiangolo.com/advanced/custom-response/#html-response)并提交一份HTML <form> https://www.w3schools.com/html/html_forms.asp,如图所示这个答案 https://stackoverflow.com/a/70777217/17865804.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

FastAPI 的 RedirectResponse 在 Swagger UI 中无法按预期工作 的相关文章

随机推荐