<?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; 李辉 / Grey Li</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>Thu, 06 Nov 2025 11:36:11 +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; 李辉 / Grey Li</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[计算机与编程]]></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<br />
</h2>
<p>
	在 HTML 文件里，引入这些静态文件需要给出资源所在的 URL。为了更加灵活，这些文件的 URL 可以通过 Flask 提供的&nbsp;<code>url_for()</code>&nbsp;函数来生成。
</p>
<p>
	在第 2 章的最后，我们学习过&nbsp;<code>url_for()</code>&nbsp;函数的用法，传入端点值（视图函数的名称）和参数，它会返回对应的 URL。对于静态文件，需要传入的端点值是&nbsp;<code>static</code>，同时使用<code>filename</code>&nbsp;参数来传入相对于 static 文件夹的文件路径。
</p>
<p>
	假如我们在 static 文件夹的根目录下面放了一个 foo.jpg 文件，下面的调用可以获取它的 URL：
</p>
<pre>
&lt;img src=&quot;{{ url_for(&#39;static&#39;, filename=&#39;foo.jpg&#39;) }}&quot;&gt;</pre>
<p>
	花括号部分的调用会返回&nbsp;<code>/static/foo.jpg</code>。
</p>
<p>
	<strong>提示</strong>&nbsp;在 Python 脚本里，<code>url_for()</code>&nbsp;函数需要从&nbsp;<code>flask</code>&nbsp;包中导入，而在模板中则可以直接使用，因为 Flask 把一些常用的函数和对象添加到了模板上下文（环境）里。
</p>
<h2>
	添加 Favicon<br />
</h2>
<p>
	Favicon（favourite icon） 是显示在标签页和书签栏的网站头像。你需要准备一个 ICO、PNG 或 GIF 格式的图片，大小一般为 16&times;16、32&times;32、48&times;48 或 64&times;64 像素。把这个图片放到 static 目录下，然后像下面这样在 HTML 模板里引入它：
</p>
<p>
	<em>templates/index.html：引入 Favicon</em>
</p>
<pre>
&lt;head&gt;
    ...
    &lt;link rel=&quot;icon&quot; href=&quot;{{ url_for(&#39;static&#39;, filename=&#39;favicon.ico&#39;) }}&quot;&gt;
&lt;/head&gt;</pre>
<p>
	保存后刷新页面，即可在浏览器标签页上看到这个图片。
</p>
<h2>
	添加图片<br />
</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=&quot;Avatar&quot; src=&quot;{{ url_for(&#39;static&#39;, filename=&#39;images/avatar.png&#39;) }}&quot;&gt;
    {{ name }}&#39;s Watchlist
&lt;/h2&gt;
...
&lt;img alt=&quot;Walking Totoro&quot; src=&quot;{{ url_for(&#39;static&#39;, filename=&#39;images/totoro.gif&#39;) }}&quot;&gt;</pre>
<p>
	<strong>提示</strong>&nbsp;这两张图片你可以自己替换为任意的图片（注意更新文件名），也可以在示例程序的&nbsp;<a href="https://github.com/greyli/watchlist/tree/master/static/images">GitHub 仓库</a>下载。
</p>
<h2>
	添加 CSS<br />
</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>
	接着在页面的&nbsp;<code>&lt;head&gt;</code>&nbsp;标签内引入这个 CSS 文件：
</p>
<p>
	<em>templates/index.html：引入 CSS 文件</em>
</p>
<pre>
&lt;head&gt;
    ...
    &lt;link rel=&quot;stylesheet&quot; href=&quot;{{ url_for(&#39;static&#39;, filename=&#39;style.css&#39;) }}&quot; type=&quot;text/css&quot;&gt;
&lt;/head&gt;</pre>
<p>
	最后要为对应的元素设置&nbsp;<code>class</code>&nbsp;属性值，以便和对应的 CSS 定义关联起来：
</p>
<p>
	<em>templates/index.html：添加 class 属性</em>
</p>
<pre>
&lt;h2&gt;
    &lt;img alt=&quot;Avatar&quot; class=&quot;avatar&quot; src=&quot;{{ url_for(&#39;static&#39;, filename=&#39;images/avatar.png&#39;) }}&quot;&gt;
    {{ name }}&#39;s Watchlist
&lt;/h2&gt;
...
&lt;ul class=&quot;movie-list&quot;&gt;
    ...
&lt;/ul&gt;
&lt;img alt=&quot;Walking Totoro&quot; class=&quot;totoro&quot; src=&quot;{{ url_for(&#39;static&#39;, filename=&#39;images/totoro.gif&#39;) }}&quot;&gt;</pre>
<p>
	最终的页面如下图所示（你可以自由修改 CSS 定义，我已经尽力了）：
</p>
<p>
	<a href="https://github.com/greyli/flask-tutorial/blob/master/chapters/images/4-1.png" rel="noopener noreferrer" target="_blank"><img alt="4-1" src="https://github.com/greyli/flask-tutorial/raw/master/chapters/images/4-1.png" /></a>
</p>
<h2>
	本章小结<br />
</h2>
<p>
	主页现在基本成型了，接下来我们会慢慢完成程序的功能。结束前，让我们提交代码：
</p>
<pre>
$ git add .
$ git commit -m &quot;Add static files&quot;
$ git push</pre>
<p>
	<strong>提示</strong> 你可以在 GitHub 上查看本书示例程序的对应 commit：<a href="https://github.com/greyli/watchlist/commit/e51c579735ae837824f10af5c1b7d454014d3c59" spellcheck="false">e51c579</a>。
</p>
<h2>
	进阶提示<br />
</h2>
<ul>
<li>
		如果你对 CSS 很头疼，可以借助前端框架来完善页面样式，比如&nbsp;<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>&nbsp;等。它们提供了大量的 CSS 定义和动态效果，使用起来非常简单。
	</li>
<li>
		扩展&nbsp;<a href="https://github.com/greyli/bootstrap-flask">Bootstrap-Flask</a>&nbsp;可以简化在 Flask 项目里使用 Bootstrap 4 的步骤。
	</li>
<li>
		本书主页 &amp; 相关资源索引：<a data-editable="true" data-offset-key="eh3t9-1-0" href="http://helloflask.com/tutorial" target="_blank">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>
