<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>静态文件 &#8211; greydreaming</title>
	<atom:link href="https://greyli.com/tag/%e9%9d%99%e6%80%81%e6%96%87%e4%bb%b6/feed/" rel="self" type="application/rss+xml" />
	<link>https://greyli.com</link>
	<description>做了一个灰色的梦</description>
	<lastBuildDate>Mon, 09 Nov 2026 15:05:39 +0000</lastBuildDate>
	<language>zh-CN</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.9.26</generator>

<image>
	<url>https://greyli.com/wp-content/uploads/2025/03/avatar-500-compressed-144x144.jpg</url>
	<title>静态文件 &#8211; greydreaming</title>
	<link>https://greyli.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>《Flask 入门教程》第 4 章：使用静态文件</title>
		<link>https://greyli.com/flask-tutorial-chapter-4-static-files/</link>
		<comments>https://greyli.com/flask-tutorial-chapter-4-static-files/#respond</comments>
		<pubDate>Wed, 19 Dec 2018 08:26:45 +0000</pubDate>
		<dc:creator><![CDATA[李辉]]></dc:creator>
				<category><![CDATA[Tech Notes]]></category>
		<category><![CDATA[Flask]]></category>
		<category><![CDATA[Flask 入门教程]]></category>
		<category><![CDATA[静态文件]]></category>

		<guid isPermaLink="false">http://greyli.com/?p=2066</guid>
		<description><![CDATA[静态文件（static files）和我们的模板概念相反，指的是内容不需要动态生成的文件。比如图片、CSS 文 [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>静态文件（static files）和我们的模板概念相反，指的是内容不需要动态生成的文件。比如图片、CSS 文件和 JavaScript 脚本等。</p>
<p>在 Flask 中，我们需要创建一个 static 文件夹来保存静态文件，它应该和程序模块、templates 文件夹在同一目录层级，所以我们在项目根目录创建它：</p>
<pre>$ mkdir static</pre>
<h2>生成静态文件 URL</h2>
<p>在 HTML 文件里，引入这些静态文件需要给出资源所在的 URL。为了更加灵活，这些文件的 URL 可以通过 Flask 提供的 <code>url_for()</code> 函数来生成。</p>
<p>在第 2 章的最后，我们学习过 <code>url_for()</code> 函数的用法，传入端点值（视图函数的名称）和参数，它会返回对应的 URL。对于静态文件，需要传入的端点值是 <code>static</code>，同时使用<code>filename</code> 参数来传入相对于 static 文件夹的文件路径。</p>
<p>假如我们在 static 文件夹的根目录下面放了一个 foo.jpg 文件，下面的调用可以获取它的 URL：</p>
<pre>&lt;img src="{{ url_for('static', filename='foo.jpg') }}"&gt;</pre>
<p>花括号部分的调用会返回 <code>/static/foo.jpg</code>。</p>
<p><strong>提示</strong> 在 Python 脚本里，<code>url_for()</code> 函数需要从 <code>flask</code> 包中导入，而在模板中则可以直接使用，因为 Flask 把一些常用的函数和对象添加到了模板上下文（环境）里。</p>
<h2>添加 Favicon</h2>
<p>Favicon（favourite icon） 是显示在标签页和书签栏的网站头像。你需要准备一个 ICO、PNG 或 GIF 格式的图片，大小一般为 16×16、32×32、48×48 或 64×64 像素。把这个图片放到 static 目录下，然后像下面这样在 HTML 模板里引入它：</p>
<p><em>templates/index.html：引入 Favicon</em></p>
<pre>&lt;head&gt;
    ...
    &lt;link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}"&gt;
&lt;/head&gt;</pre>
<p>保存后刷新页面，即可在浏览器标签页上看到这个图片。</p>
<h2>添加图片</h2>
<p>为了让页面不那么单调，我们来添加两个图片：一个是显示在页面标题旁边的头像，另一个是显示在页面底部的龙猫动图。我们在 static 目录下面创建一个子文件夹 images，把这两个图片都放到这个文件夹里：</p>
<pre>$ cd static
$ mkdir images</pre>
<p>创建子文件夹并不是必须的，这里只是为了更好的组织同类文件。同样的，如果你有多个 CSS 文件，也可以创建一个 css 文件夹来组织他们。下面我们在页面模板中添加这两个图片，注意填写正确的文件路径：</p>
<p><em>templates/index.html：添加图片</em></p>
<pre>&lt;h2&gt;
    &lt;img alt="Avatar" src="{{ url_for('static', filename='images/avatar.png') }}"&gt;
    {{ name }}'s Watchlist
&lt;/h2&gt;
...
&lt;img alt="Walking Totoro" src="{{ url_for('static', filename='images/totoro.gif') }}"&gt;</pre>
<p><strong>提示</strong> 这两张图片你可以自己替换为任意的图片（注意更新文件名），也可以在示例程序的 <a href="https://github.com/greyli/watchlist/tree/master/static/images">GitHub 仓库</a>下载。</p>
<h2>添加 CSS</h2>
<p>虽然添加了图片，但页面还是非常简陋，因为我们还没有添加 CSS 定义。下面在 static 目录下创建一个 CSS 文件 style.css，内容如下：</p>
<p><em>static/style.css：定义页面样式</em></p>
<pre>/* 页面整体 */
body {
    margin: auto;
    max-width: 580px;
    font-size: 14px;
    font-family: Helvetica, Arial, sans-serif;
}

/* 页脚 */
footer {
    color: #888;
    margin-top: 15px;
    text-align: center;
    padding: 10px;
}

/* 头像 */
.avatar {
    width: 40px;
}

/* 电影列表 */
.movie-list {
    list-style-type: none;
    padding: 0;
    margin-bottom: 10px;
    box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.16), 0 2px 10px 0 rgba(0, 0, 0, 0.12);
}

.movie-list li {
    padding: 12px 24px;
    border-bottom: 1px solid #ddd;
}

.movie-list li:last-child {
    border-bottom:none;
}

.movie-list li:hover {
    background-color: #f8f9fa;
}

/* 龙猫图片 */
.totoro {
    display: block;
    margin: 0 auto;
    height: 100px;
}</pre>
<p>接着在页面的 <code>&lt;head&gt;</code> 标签内引入这个 CSS 文件：</p>
<p><em>templates/index.html：引入 CSS 文件</em></p>
<pre data-eusoft-scrollable-element="1">&lt;head&gt;
    ...
    &lt;link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}" type="text/css"&gt;
&lt;/head&gt;</pre>
<p>最后要为对应的元素设置 <code>class</code> 属性值，以便和对应的 CSS 定义关联起来：</p>
<p><em>templates/index.html：添加 class 属性</em></p>
<pre data-eusoft-scrollable-element="1">&lt;h2&gt;
    &lt;img alt="Avatar" class="avatar" src="{{ url_for('static', filename='images/avatar.png') }}"&gt;
    {{ name }}'s Watchlist
&lt;/h2&gt;
...
&lt;ul class="movie-list"&gt;
    ...
&lt;/ul&gt;
&lt;img alt="Walking Totoro" class="totoro" src="{{ url_for('static', filename='images/totoro.gif') }}"&gt;</pre>
<p>最终的页面如下图所示（你可以自由修改 CSS 定义，我已经尽力了）：</p>
<p><a href="https://github.com/greyli/flask-tutorial/blob/master/chapters/images/4-1.png" target="_blank" rel="noopener noreferrer"><img src="https://github.com/greyli/flask-tutorial/raw/master/chapters/images/4-1.png" alt="4-1" /></a></p>
<h2>本章小结</h2>
<p>主页现在基本成型了，接下来我们会慢慢完成程序的功能。结束前，让我们提交代码：</p>
<pre>$ git add .
$ git commit -m "Add static files"
$ git push</pre>
<p><strong>提示</strong> 你可以在 GitHub 上查看本书示例程序的对应 commit：<a spellcheck="false" href="https://github.com/greyli/watchlist/commit/e51c579735ae837824f10af5c1b7d454014d3c59">e51c579</a>。</p>
<h2>进阶提示</h2>
<ul>
<li>如果你对 CSS 很头疼，可以借助前端框架来完善页面样式，比如 <a href="https://getbootstrap.com/" rel="nofollow">Bootstrap</a>、<a href="http://semantic-ui.com/" rel="nofollow">Semantic-UI</a>、<a href="https://foundation.zurb.com/" rel="nofollow">Foundation</a> 等。它们提供了大量的 CSS 定义和动态效果，使用起来非常简单。</li>
<li>扩展 <a href="https://github.com/greyli/bootstrap-flask">Bootstrap-Flask</a> 可以简化在 Flask 项目里使用 Bootstrap 4 的步骤。</li>
<li>本书主页 &amp; 相关资源索引：<a href="http://helloflask.com/tutorial" target="_blank" rel="noopener" data-editable="true" data-offset-key="eh3t9-1-0">http://helloflask.com/tutorial</a>。</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>https://greyli.com/flask-tutorial-chapter-4-static-files/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
