前提
FastAPIでAPIを作成し、gunicornを介し、apacheサーバー経由で公開しようと試みました。
実現したいこと
上記「前提」を達成するために、
- APIの作成とgunicornで起動
- Apacheウェブサーバーでリバースプロキシを組み、公開
を行おうとしました。
しかし、APIのエンドポイントの最後の"/"(スラッシュ)の有無によってlocalhost:8080に転送される問題が発生しました。
localhostに転送されると、CORSでエラーになり、セキュリティ上問題があると考えられます。
この転送問題を解決したいです。
該当のソースコード
Apache サイト設定:
<VirtualHost *:80> ServerName api.example.com ServerAdmin admin@example.com DocumentRoot /path/to/front_end ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined ProxyRequests Off ProxyPass / http://localhost:8080/ ProxyPassReverse / https://localhost:8080/ </VirtualHost>
APIコード(main.py):
python
1from fastapi import FastAPI 2from fastapi.responses import ORJSONResponse 3 4app = FastAPI(title="Test API", description="Test API", version="0.0.1", default_response_class=ORJSONResponse) 5 6@app.get("/test") 7def test(): 8 return "Hello world"
Gunicorn 設定ファイル(gunicorn_conf.py):
python
1#An server configuration for production 2 3import multiprocessing 4import os 5 6name = "gunicorn" 7 8if not os.path.exists("./logs/"): 9 os.mkdir("./logs") 10accesslog = os.path.abspath("./logs/access.log") 11errorlog = os.path.abspath("./logs/error.log") 12 13bind = "0.0.0.0:8080" 14 15worker_class = "uvicorn.workers.UvicornWorker" 16workers = multiprocessing.cpu_count() * 2 + 1 17worker_connections = 1024 18backlog = 2048 19max_requests = 5120 20timeout = 120 21keepalive = 2 22reuse_port=True 23#daemon=True 24 25debug = os.environ.get("DEBUG", "false") == "true"
Gunicorn起動コマンド:
shell
1/path/to/gunicorn -c gunicorn_conf.py main:app
試したこと
/を最後につけたAPIを定義する、リダイレクトを行わないようにFastAPIを設定する(ただし、本来達成したい仕様と異なるため避けたい)
補足情報(FW/ツールのバージョンなど)
Python 3.10
FastAPI 0.79.1(full install)
Apache 2 on Ubuntu 22.04
宜しくおねがいします。
回答1件
あなたの回答
tips
プレビュー