4
votes

Usually, the problem is how to serve static files in development environment, while in my case it is the opposite. So I've deployed a Flask application using Apache and mod_wsgi, configured Apache to serve my static files at /static url. And now I'm not sure, whether those files are being served by Apache or by Flask, since flask is also using by default the same path for static.

In templates I use url_for("static", filename="style.css"). And it works fine. But this is the problem, because I don't know what is serving my static files. Of course, I can be sure that Apache is serving, if I change every template to have hardcoded path and something different than default Flask, but this doesn't sound like the right solution.

So to sum up my question: how to use url_for(static) in Flask (templates) and be sure, that Flask is not serving them for me?

Thanks, Rapolas K.

2

2 Answers

6
votes
  1. Set another static folder (you will need also create empty folder on file system):

    app = Flask(__name__, static_url_path='static', static_folder='static_test')
    

    So if you get 404 then files serving by flask else apache.

  2. Add test folder and map apache as for static folder.

    So if you get content from test folder then files serving by apache else flask.

  3. Break any static endpoint requests:

    @app.before_request
    def break_static():
        if request.endpoint == 'static':
            abort(404)
        return None
    

    or

    class YourApp(Flask):
        def send_static_file(self, filename):
            abort(404)
    

    So if you get 404 then files serving by flaks else apache.

But you enough once test this case if you realy not sure. If apache configuration will not changing then static serving behaviour will not changing too.

0
votes

You can be sure as long as you have this:

if __name__ == '__main__':
    app.run()

The app.run() call actually starts the local development server. In production, you will/should never have to call this and hence nothing can be served by the dev. server since it is never started.