Zab*_*azi 16 ssl http-redirect python-3.x fastapi uvicorn
我正在尝试使用 SSL 运行 fastapi 应用程序。
我正在使用 uvicorn 运行该应用程序。
我可以使用 HTTP 在端口 80 上运行服务器,
if __name__ == '__main__':
uvicorn.run("main:app", port=80, host='0.0.0.0', reload = True, reload_dirs = ["html_files"])
Run Code Online (Sandbox Code Playgroud)
要使用 HTTPS 运行端口,我执行以下操作:
if __name__ == '__main__':
uvicorn.run("main:app", port=443, host='0.0.0.0', reload = True, reload_dirs = ["html_files"], ssl_keyfile="/etc/letsencrypt/live/my_domain/privkey.pem", ssl_certfile="/etc/letsencrypt/live/my_domain/fullchain.pem")
Run Code Online (Sandbox Code Playgroud)
我如何运行两者或简单地集成 https 重定向?
注意:这是在我不想使用 nginx 的服务器上进行的设置,我知道如何使用 nginx 来实现 https 重定向。
aar*_*ron 10
运行子进程以将重定向响应从一个端口返回到另一个端口。
主要.py:
if __name__ == '__main__':
Popen(['python', '-m', 'https_redirect']) # Add this
uvicorn.run(
'main:app', port=443, host='0.0.0.0',
reload=True, reload_dirs=['html_files'],
ssl_keyfile='/path/to/certificate-key.pem',
ssl_certfile='/path/to/certificate.pem')
Run Code Online (Sandbox Code Playgroud)
https_redirect.py:
import uvicorn
from fastapi import FastAPI
from starlette.requests import Request
from starlette.responses import RedirectResponse
app = FastAPI()
@app.route('/{_:path}')
async def https_redirect(request: Request):
return RedirectResponse(request.url.replace(scheme='https'))
if __name__ == '__main__':
uvicorn.run('https_redirect:app', port=80, host='0.0.0.0')
Run Code Online (Sandbox Code Playgroud)
Chr*_*ris 10
使用HTTPSRedirectMiddleware。这将强制重定向到https任何传入的请求。
from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware
app.add_middleware(HTTPSRedirectMiddleware)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37872 次 |
| 最近记录: |