Search code examples
pythonflaskstatic-filesblueprint

send_static_file not picking up from static folder at root in Blueprint


From the views.py inside my blueprint, im trying to use the send_static_file to deliver an index.html and just cant get it to work

I have a blueprint called main which I initialize as such in the __init__.py under the blueprint folder mod_main

from flask import Blueprint 
mod_main = Blueprint('main',name,static_folder='/static', static_url_path='/static') 
from . import views

In my main app initialization in the __init__.py under the root app folder

app = Flask(__name__)
from .mod_main import mod_main as main_blueprint
app.register_blueprint(main_blueprint,url_prefix='/main')

Under the views.py file in the blueprint main (mod_main folder)

@mod_main.route('/')
def index():
    return mod_main.send_static_file('index.html')

But it keeps resolving to 404 Not found. Any clue how i can serve the index.html that is under the static folder in the root app folder (I can get it to work if i create a static folder inside the blueprint. But i would like to deliver it from the root app)

Heres the structure with the essential files

app
|
-- mod_main/
   |
    -- views.py
    -- __init__.py

-- __init__.py

-- static /
   |
    -- index.html

Solution

  • You've told the blueprint to find the static files in /static, or, a folder called static in the root of your file system. Assuming you don't want to change it to static and move the folder into mod_main, there are a couple of different approaches you can take.

    If you want to make the distinction between static files for the app and static files for the blueprint, you can serve the file through the current app.

    # mod_main/views.py
    from flask import current_app
    
    from . import mod_main
    
    
    @mod_main.route('/')
    def index():
        return current_app.send_static_file('index.html')
    

    If, however, you intend to use the existing static as your only static folder, you need to update your blueprint to use this folder.

    # mod_main/__init__.py
    import os
    
    from flask import Blueprint
    
    static_folder = os.path.join(os.pardir, 'static')
    mod_main = Blueprint(
        'main', __name__, static_folder=static_folder, static_url_path='/static')
    
    from . import views