Skip to content Skip to sidebar Skip to footer

Serve Static Files From Blueprints Without Url Prefix

For development, I'd like to serve static files from the blueprint's static folder. However, I don't want to load all files via the url prefix of the blueprint. Is there a possibil

Solution 1:

You can't with default flask mechanism.

In your your example you will create 3 rules for static forlder:

Rule "/assets/<path:filename>"for"static" endpoint
Rule "/assets/<path:filename>"for"foo.static" endpoint
Rule "/assets/<path:filename>"for"bar.static" endpoint

When flask will match your URL to rule it take first match and return it. In this case it return static endpoint rule. After will dispatched function for this endpoint, e.g. one folder.

PS. I don't sure that exactly static endpoint, better check Map.update method.

But you always can write own request descriptor, which will look at blue prints folders:

classMyApp(Flask):
    defstatic_dispatchers(self):
        yieldsuper(MyApp, self).send_static_file
        for blueprint in self.blueprints.values():
            yield blueprint.send_static_file

    defsend_static_file(self, filename):
        last_exception = Nonefor static_dispatcher in self.static_dispatchers():
            try:
                return static_dispatcher(filename)
            except NotFound as e:
                last_exception = e
        raise last_exception

PS. This example doesn't include the blueprint registration sequence, because it stored in dict.

But if you have two files with same name, then first file will processed. For example if you have next structure:

/static
/static/app.js "console.log('app');"
/foo/static/app.js "console.log('foo app');"
/foo/static/blue.js "console.log('foo blue');"
/foo/static/foo.js "console.log('foo self');"
/bar/static/app.js "console.log('bar app');"
/bar/static/blue.js "console.log('foo blue');"
/bar/static/bar.js "console.log('bar self');"

And include scripts to page:

<scriptsrc="{{ url_for('static', filename='app.js') }}"></script><scriptsrc="{{ url_for('foo.static', filename='app.js') }}"></script><scriptsrc="{{ url_for('bar.static', filename='app.js') }}"></script><scriptsrc="{{ url_for('foo.static', filename='blue.js') }}"></script><scriptsrc="{{ url_for('bar.static', filename='blue.js') }}"></script><scriptsrc="{{ url_for('foo.static', filename='foo.js') }}"></script><scriptsrc="{{ url_for('bar.static', filename='bar.js') }}"></script>

You will have next result:

app
app
app
foo blue(or bar blue)
foo blue(or bar blue)
foo self
bar self

For js and css can concatenate files with same path, but can't do this for images.

However I prefer use unique URL prefix for each blueprint, because it simple with url_for.

Post a Comment for "Serve Static Files From Blueprints Without Url Prefix"