Python进阶-day23:web开发入门
课程目标
- 理解 Web 开发基础:掌握 Flask 框架的核心概念,包括路由、模板和请求处理。
- 搭建动态 Web 应用:通过 Flask 创建一个简单的个人博客网站,能够展示文章列表和文章详情。
- 实践技能:学会使用模板渲染动态内容,处理用户请求,并组织项目结构。
术语解释
- Flask:一个轻量级的 Python Web 框架,适合快速构建小型到中型 Web 应用。它的核心功能包括路由、模板渲染和请求处理。
- 路由(Routing):将特定的 URL 映射到 Python 函数的过程。例如,访问 /about 时调用一个显示“关于”页面的函数。
- 模板(Template):用于生成动态 HTML 的文件,通常使用 Jinja2 模板引擎,允许在 HTML 中嵌入 Python 代码。
- Jinja2:Flask 默认使用的模板引擎,支持变量、循环、条件语句等动态内容生成。
- HTTP 请求:客户端(如浏览器)向服务器发送的请求,包括 GET(获取数据)和 POST(提交数据)等方法。
- 虚拟环境(Virtual Environment):隔离的 Python 环境,用于管理项目依赖,避免包冲突。
课程内容:Flask Web 开发入门
准备工作
- 安装 Flask:bash
- pip install flask
- 创建项目目录结构:
- myblog/ ├── app.py # 主应用文件 ├── templates/ # 模板文件夹 │ ├── base.html # 基础模板 │ ├── index.html # 首页模板 │ └── post.html # 文章详情模板 └── static/ # 静态文件(如 CSS) └── style.css
代码实现:简单个人博客网站
1. 主应用文件(app.py)
python
from flask import Flask, render_template
# 初始化 Flask 应用
app = Flask(__name__)
# 模拟博客文章数据(实际项目中通常从数据库获取)
posts = [
{"id": 1, "title": "我的第一篇博客", "content": "这是博客的正文内容,欢迎体验!"},
{"id": 2, "title": "Flask 学习笔记", "content": "Flask 是一个轻量级框架..."}
]
# 首页路由:显示文章列表
@app.route('/')
def index():
return render_template('index.html', posts=posts)
# 文章详情路由:根据文章 ID 显示具体文章
@app.route('/post/<int:post_id>')
def post(post_id):
# 查找对应 ID 的文章,若不存在返回 None
post = next((p for p in posts if p['id'] == post_id), None)
if post is None:
return "文章不存在", 404
return render_template('post.html', post=post)
# 启动 Flask 应用
if __name__ == '__main__':
app.run(debug=True)
代码注释:
- Flask(name):创建 Flask 应用实例,name 用于定位模板和静态文件。
- @app.route('/'):定义路由,/ 表示首页,绑定到 index 函数。
- render_template:渲染指定模板,并将数据(如 posts)传递给模板。
- /post/int:post_id:动态路由,捕获 URL 中的 post_id 并转换为整数。
- debug=True:启用调试模式,方便开发时查看错误并自动重载。
2. 基础模板(templates/base.html)
html
<!DOCTYPE html>
<html>
<head>
<title>我的博客</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<header>
<h1>欢迎访问我的博客</h1>
<nav>
<a href="{{ url_for('index') }}">首页</a>
</nav>
</header>
<main>
{% block content %}
{% endblock %}
</main>
</body>
</html>
术语与注释:
- {{ url_for('static', filename='style.css') }}:生成静态文件 URL,指向 static/style.css。
- {% block content %}:Jinja2 的块语法,允许子模板填充具体内容。
- {{ url_for('index') }}:生成指向 index 路由的 URL,增强代码可维护性。
3. 首页模板(templates/index.html)
html
{% extends 'base.html' %}
{% block content %}
<h2>文章列表</h2>
<ul>
{% for post in posts %}
<li>
<a href="{{ url_for('post', post_id=post.id) }}">{{ post.title }}</a>
</li>
{% endfor %}
</ul>
{% endblock %}
术语与注释:
- {% extends 'base.html' %}:继承基础模板,复用通用布局。
- {% for post in posts %}:Jinja2 循环,遍历传递的 posts 列表。
- url_for('post', post_id=post.id):生成文章详情页的 URL,动态传入 post_id。
4. 文章详情模板(templates/post.html)
html
{% extends 'base.html' %}
{% block content %}
<h2>{{ post.title }}</h2>
<p>{{ post.content }}</p>
<a href="{{ url_for('index') }}">返回首页</a>
{% endblock %}
术语与注释:
- {{ post.title }}:显示传递的 post 对象的 title 属性。
- <a href="{{ url_for('index') }}">:提供返回首页的链接。
5. 样式文件(static/style.css)
css
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
}
header {
text-align: center;
margin-bottom: 20px;
}
nav a {
margin: 0 10px;
text-decoration: none;
color: blue;
}
ul {
list-style-type: none;
padding: 0;
}
li {
margin: 10px 0;
}
术语与注释:
- static/:Flask 的静态文件夹,用于存放 CSS、JavaScript 和图片等文件。
- CSS 样式:美化页面布局,确保内容清晰易读。
运行项目
- 确保 Flask 已安装,项目文件结构正确。
- 在终端运行:bash
- python app.py
- 打开浏览器,访问 http://127.0.0.1:5000,即可看到博客网站。
练习:扩展功能
- 添加文章分类:在 posts 数据中加入 category 字段,并在首页按分类过滤文章。
- 实现文章搜索:添加一个搜索表单,允许用户通过关键词查找文章。
- 美化界面:引入 Bootstrap 或其他 CSS 框架,优化博客的视觉效果。
- 持久化存储:使用 SQLite 数据库存储文章数据,替换硬编码的 posts 列表。
通过本课程,学习者能够:
- 掌握 Flask 的路由和模板渲染机制。
- 理解 Jinja2 模板引擎的基本语法。
- 搭建一个功能简单的博客网站,并具备扩展能力。
- 熟悉 Web 开发的基本流程,包括项目结构和静态文件管理。
如果需要更详细的代码解释或扩展功能的实现,请随时告知!