Flask, Keep getting 404 serving static files using send_static_file

后端 未结 5 747
星月不相逢
星月不相逢 2020-12-28 13:46

I followed the instructions from How to serve static files in Flask, but still couldn\'t get it working.

Here\'s my project structure:

Project_path           


        
相关标签:
5条回答
  • 2020-12-28 14:00

    One possible cause of 404 error for pages you just added (even if programmed correctly), is if you have previous versions of the script (.py file) still running: make sure to close out and end (terminate) the process.

    0 讨论(0)
  • 2020-12-28 14:04

    All you need to do is, pass the static_folder parameter to the initiator:

    static_url_path – can be used to specify a different path for the static files on the web. Defaults to the name of the static_folder folder.

    static_folder – the folder with static files that should be served at static_url_path. Defaults to the 'static' folder in the root path of the application.

    app = Flask(__name__, static_folder=os.path.abspath('/foo/bar/zoo/'))
    

    Now, flask will look for a directory named static in /foo/bar/zoo from where to serve static files. You only use send_from_directory if you are serving media files which may not be in the same location as static files.

    0 讨论(0)
  • 2020-12-28 14:12

    Finally got it working. use flask.send_from_directory

    from flask import send_from_directory
    
    @app.route('/js/<path:filename>')
    def serve_static(filename):
        root_dir = os.path.dirname(os.getcwd())
        return send_from_directory(os.path.join(root_dir, 'static', 'js'), filename)
    

    It is now clear to me that flask really hate people putting app.py or in my case main.py into a subdirectory. Use send_static_file only if your static folder is what flask thinks to be, i.e. a folder with name static in the same directory with app.py.

    0 讨论(0)
  • 2020-12-28 14:12

    for me this one worked :

    @app.route('/static/<path:filename>')
    def serve_static(filename):
        root_dir = os.path.dirname(os.getcwd())
        return send_from_directory(os.path.join(root_dir, 'static', 'js'),   filename)       
    

    beside adding this script into init

    app._static_folder = os.path.abspath("static/")
    app = Flask(__name__)
    

    into __init__.py

    0 讨论(0)
  • 2020-12-28 14:24

    You forgot to add 'static' in the last os.path.join in the return clause.

    0 讨论(0)
提交回复
热议问题