最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - FastAPI hosted on Lambda does not serve static content - Stack Overflow

programmeradmin2浏览0评论

I have a FastAPI app hosted on AWS Lambda + Api Gateway using Mangum. However it seems not to be able to serve static content returning 404 error.

Here is how static directory is mounted

application = FastAPI(title="MyApp")

static_directory = Path(__file__).parent / "static"
application.mount(
    f"{settings.formatted_api_stage}/static",
    StaticFiles(directory=static_directory, check_dir=True),
    name="static",
)

settings.formatted_api_stage corresponds to API Gateway stage like /dev in /

Mangum handler

handler = Mangum(
    application, lifespan="off", api_gateway_base_path=settings.formatted_api_stage
)

AWS infra is managed using CDK

fastapi_lambda = PythonFunction(
    self,
    "MyLambda",
    entry="../app",
    index="main.py",
    handler="handler",
    runtime=_lambda.Runtime.PYTHON_3_13,
    role=lambda_role,
    memory_size=512,
    timeout=Duration.seconds(5),
    bundling=BundlingOptions(asset_excludes=["*.pyc", "__pycache__/"]),
)

api = apigateway.LambdaRestApi(
    self,
    "MyAPI",
    handler=fastapi_lambda,
    proxy=True,
    deploy_options=apigateway.StageOptions(
        stage_name=api_stage,
    ),
)

Then in the templates I reference static content like

<link rel="stylesheet" href="{{ url_for('static', path='/css/style.css') }}" />

But it results in a 404 error.

I can verify that static folder is packaged ok and is present in the same folder as main.py in the lambda bundle.

The app works as expected when run locally.

发布评论

评论列表(0)

  1. 暂无评论