Home > Enterprise >  Python Flask: forbidden access to static files in aws lambda
Python Flask: forbidden access to static files in aws lambda

Time:11-05

I deployed my flask app on the aws lambda service, although the app works fine, it cannot get .css and .js files from static folder, 403 FORBIDDEN error is returned when trying to access them.

I think the issue might be in my IAM user roles I use to deploy my application. I gave him following roles: AmazonAPIGatewayInvokeFullAccess, AdministratorAccess and AmazonAPIGatewayAdministrator as well as IAMFullAccess user group but to no effect. I'm using serverless to deploy my app.

Here are my app files:

serverless.yml


service: serverless-flask

plugins:
  - serverless-python-requirements
  - serverless-wsgi

custom:
  wsgi:
    app: run.app
    packRequirements: false
  pythonRequirements:
    dockerizePip: non-linux

provider:
  name: aws
  runtime: python3.9
  stage: dev
  region: eu-central-1

package:
  exclude:
    - node_modules/**
    - venv/**

functions:
  app:
    handler: wsgi_handler.handler
    events:
      - http: ANY /
      - http: "ANY {proxy }"

Project files:

├── my_app
│   ├── __init__.py
│   ├── static
│   │   ├── css
│   │   │   └── main.css
│   │   ├── js
│   │   │   └── main.js
│   │   ├── package.json
│   │   └── package-lock.json
│   ├── templates
│   │   ├── index.html
│   │   └── layout.html
│   └── utils
│       ├── reader.py
│       └── __init__.py
├── package.json
├── package-lock.json
├── requirements.txt
├── run.py
└── serverless.yml

App creation file:

from flask import Flask, render_template
import os


def create_app():
    app = Flask(__name__, static_folder="static", static_url_path="/static")

    @app.route("/", methods=["GET"])
    def index():
        sample_data = {
            'data': 'sample data'
        }
        return render_template("index.html", data=sample_data)

    return app

CodePudding user response:

Ok, I figured it out. Just had to rename folder static to something else, for some reason AWS blocks access to folder named static. I renamed folder to public but it works with any name as long as it's not static

Here is my project structure updated:

├── my_app
│   ├── __init__.py
│   ├── public
│   │   ├── css
│   │   │   └── main.css
│   │   ├── js
│   │   │   └── main.js
│   │   ├── package.json
│   │   └── package-lock.json
│   ├── templates
│   │   ├── index.html
│   │   └── layout.html
│   └── utils
│       ├── reader.py
│       └── __init__.py
├── package.json
├── package-lock.json
├── requirements.txt
├── run.py
└── serverless.yml
  • Related