1. 静态文件与 web 程序的组成
Web 程序不是仅由
- Python 代码
- 模板组成,
- 静态文件,
- HTML 代码中引用的图片、
- JavaScript 源码文件、
- CSS;
>>> app = Flask(__name__)>>> app.url_mapMap([<Rule '/static/<filename>' (GET, OPTIONS, HEAD) -> static>])
- 1
- 2
- 3
当我们查看 URL 映射时,其中默认就有一个 static 路由,
当然,当我们使用 bootstrap 时:
>> from flask_bootstrap import Bootstrap>> bootstrap = Bootstrap(app)>> app.url_mapMap([<Rule '/static/bootstrap/<filename>' (GET, OPTIONS, HEAD) -> bootstrap.static>, <Rule '/static/<filename>' (GET, OPTIONS, HEAD) -> static>])
- 1
- 2
- 3
- 4
- 5
当我们在认为添加新的路由时:
@app.route('/')def index(): return '<h1>hello world!</h1>'>> app.url_mapMap([<Rule '/' (GET, OPTIONS, HEAD) -> index>, <Rule '/static/bootstrap/<filename>' (GET, OPTIONS, HEAD) -> bootstrap.static>, <Rule '/static/<filename>' (GET, OPTIONS, HEAD) -> static>])
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
对静态文件的引用被当做一个特殊的路由,/static/<filename>
。例如,调用:
url_for('static', filename='css/styles.css', _external=True)
- 1
得到的结果是
http://localhost:5000/static/css/styles.css
- 1
默认设置下,Flask 在程序根目录中名为 static 的子目录中寻找静态文件。如果需要,可在static 文件夹存放文件。服务器收到前面的 URL 后,会生成一个响应,包含文件系统中 static/css/styles.css
文件的内容。
2. 一个示例
如何在程序的基模板(template/base.html)中放置 favicon.ico 图标,该图标会显示在浏览器的地址栏中,
{% block head %}{{ super() }}<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico')}}" type="image/x-icon"><link rel="icon" href="{{ url_for('static', filename='favicon.ico')}}" type="image/x-icon">{% endblock %}
- 1
- 2
- 3
- 4
- 5
再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.youkuaiyun.com/jiangjunshow