在互联网时代,拥有一个个人博客不仅可以记录生活,分享见解,还能提升个人品牌。Flask 是一个轻量级的 Web 应用框架,非常适合新手入门。本文将手把手教你如何使用 Flask 搭建一个简单的个人博客。
准备工作
在开始之前,请确保你的电脑上已安装以下工具:
- Python 3.x 版本
- Flask 框架
- 一个代码编辑器(如 Visual Studio Code 或 Sublime Text)
安装 Flask
打开终端或命令提示符,输入以下命令安装 Flask:
pip install Flask
创建项目结构
首先,创建一个项目文件夹,例如 my_blog。然后,在该文件夹内创建以下文件和目录:
my_blog/
│
├── app.py
├── templates/
│ └── base.html
│ └── index.html
│ └── about.html
│ └── contact.html
│
└── static/
└── css/
└── js/
文件说明
app.py:主程序文件,负责处理请求和响应。templates/:存放 HTML 模板文件。static/:存放静态资源文件,如 CSS、JavaScript 和图片。
编写主程序
打开 app.py 文件,编写以下代码:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/about')
def about():
return render_template('about.html')
@app.route('/contact')
def contact():
return render_template('contact.html')
if __name__ == '__main__':
app.run(debug=True)
这段代码定义了三个路由,分别对应博客首页、关于我和联系方式页面。
创建 HTML 模板
在 templates/ 目录下,创建以下 HTML 文件:
base.html:基础模板,包含导航栏和页脚。index.html:首页模板,展示博客文章列表。about.html:关于我页面模板。contact.html:联系方式页面模板。
base.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
<header>
<nav>
<ul>
<li><a href="{{ url_for('index') }}">首页</a></li>
<li><a href="{{ url_for('about') }}">关于我</a></li>
<li><a href="{{ url_for('contact') }}">联系方式</a></li>
</ul>
</nav>
</header>
<main>
{{ content }}
</main>
<footer>
<p>版权所有 © 2022 我的博客</p>
</footer>
</body>
</html>
index.html
{% extends "base.html" %}
{% block content %}
<h1>我的博客</h1>
<p>这里是我的博客,记录了我的生活、学习和思考。</p>
{% endblock %}
about.html
{% extends "base.html" %}
{% block content %}
<h1>关于我</h1>
<p>我是一个热爱编程、热爱生活的人。</p>
{% endblock %}
contact.html
{% extends "base.html" %}
{% block content %}
<h1>联系方式</h1>
<p>邮箱:example@example.com</p>
<p>微信:example</p>
{% endblock %}
添加静态资源
在 static/css/ 目录下,创建一个名为 style.css 的 CSS 文件,编写以下代码:
body {
font-family: Arial, sans-serif;
}
header {
background-color: #333;
color: #fff;
}
nav ul {
list-style-type: none;
padding: 0;
}
nav ul li {
display: inline;
margin-right: 20px;
}
main {
margin: 20px;
}
footer {
background-color: #333;
color: #fff;
text-align: center;
padding: 10px;
}
运行项目
在终端或命令提示符中,进入 my_blog 目录,然后运行以下命令:
python app.py
打开浏览器,访问 http://127.0.0.1:5000/,你将看到一个简单的个人博客页面。
总结
通过本文,你学会了如何使用 Flask 框架搭建一个简单的个人博客。当然,这只是一个入门级的示例,你可以根据自己的需求添加更多功能,如文章管理、评论系统等。祝你搭建博客愉快!
