栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从没有URL前缀的蓝图中提供静态文件

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从没有URL前缀的蓝图中提供静态文件

您不能使用默认

flask
机制。

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

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

当flask将匹配您的URL进行统治时,将进行第一次匹配并返回它。在这种情况下,它返回

static
端点规则。之后将为此端点调度功能,例如一个文件夹。

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>

您将获得下一个结果:

appappappfoo blue (or bar blue)foo blue (or bar blue)foo selfbar self

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

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

url_for



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/646023.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号