1

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 possibility to configure flask, so it looks in all blueprint's static folders and returns the first file it finds? The reason for this is that when I deploy the application, the build process will pull all the files our of the blueprints and put them into a separate folder (similar to Django's collectstatics).

In other words, I have 2 blueprints: foo and bar:

app
  +--- foo
  |    +--- assets
  |    |     +--- css
  |    |     |
  |    |     +--- js
  |    +
  |    |
  |    +--- __init__.py:  foo_blueprint = Blueprint('foo', __name__, static_folder='assets')
  |
  +--- bar
       +
       |
       +--- __init__.py: bar_blueprint = Blueprint('bar', __name__, static_folder='assets')

I want all js files in the particular js subfolders to be available from the url /static/js/file.js. Is this possible?

4

1 回答 1

2

您不能使用默认flask机制。

在您的示例中,您将为静态文件夹创建 3 条规则:

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

当烧瓶将匹配您的 URL 以进行规则时,它将首先匹配并返回它。在这种情况下,它返回static端点规则。After 将为此端点调度函数,例如一个文件夹。

PS。我不确定确切的static端点,更好的检查Map.update方法。

但是您始终可以编写自己的请求描述符,它将查看蓝图文件夹:

class MyApp(Flask):
    def static_dispatchers(self):
        yield super(MyApp, self).send_static_file
        for blueprint in self.blueprints.values():
            yield blueprint.send_static_file

    def send_static_file(self, filename):
        last_exception = None
        for static_dispatcher in self.static_dispatchers():
            try:
                return static_dispatcher(filename)
            except NotFound as e:
                last_exception = e
        raise last_exception

PS。此示例不包括蓝图注册序列,因为它存储在 dict 中。

但是,如果您有两个同名文件,则将处理第一个文件。例如,如果您有下一个结构:

/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');"

并在页面中包含脚本:

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

您将得到下一个结果:

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

对于 js 和 css 可以连接具有相同路径的文件,但不能对图像执行此操作。

但是我更喜欢为每个蓝图使用唯一的 URL 前缀,因为它很简单,使用url_for.

于 2013-10-04T10:56:52.857 回答