
本教程详细介绍了如何在 flask 应用中实现多个 html 页面之间的导航。通过 `@app.route` 装饰器和 `render_template` 函数,我们将学习如何从一个 html 页面(如首页)跳转到另一个 html 页面(如注册页),并探讨了不同请求方法的处理方式,以构建结构清晰、交互流畅的 web 应用。
在构建 Flask Web 应用时,将不同的功能模块或内容展示在独立的 HTML 页面上是常见的需求。用户通过点击链接或提交表单,在这些页面之间进行跳转,从而完成一系列操作。本教程将指导您如何利用 Flask 的路由系统和模板渲染机制,实现多页面之间的无缝导航。
在深入页面导航之前,我们首先回顾 Flask 的两个核心概念:
为了使代码正常运行,请确保您的项目结构如下:
your_flask_app/
├── app.py
└── templates/
├── index.html
└── another_file.html我们将创建一个简单的 Flask 应用,包含一个首页 (index.html) 和一个注册页 (another_file.html)。用户将从首页点击链接跳转到注册页。
立即学习“前端免费学习笔记(深入)”;
首先,在 app.py 中初始化 Flask 应用,并定义一个处理根路径 / 的路由,该路由将渲染 index.html。
# app.py
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
"""
处理根路径 '/' 的请求,渲染首页。
"""
return render_template("index.html")
if __name__ == '__main__':
app.run(debug=True)在 templates/index.html 文件中,我们将创建一个简单的 HTML 页面,其中包含一个指向注册页的链接。
<!-- templates/index.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>欢迎来到首页</title>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
h1 { color: #333; }
a { color: #007bff; text-decoration: none; }
a:hover { text-decoration: underline; }
</style>
</head>
<body>
<h1>欢迎来到 Flask 应用首页</h1>
<p>点击下方链接进入注册页面:</p>
<p><a href="/register">点击注册</a></p>
</body>
</html>注意 标签的 href="/register" 属性,它指向了我们即将定义的 /register 路由。
接下来,在 app.py 中定义一个处理 /register 路径的路由,该路由将渲染 another_file.html。
# app.py (在现有代码基础上添加)
# ... (之前的导入和 app = Flask(__name__))
@app.route('/')
def index():
# ... (同上)
return render_template("index.html")
@app.route('/register', methods=['GET', 'POST'])
def register():
"""
处理 '/register' 路径的请求。
- GET 请求:显示注册表单页面。
- POST 请求:处理表单提交数据(此处为示例,实际应处理数据)。
"""
if request.method == "GET":
return render_template("another_file.html")
elif request.method == "POST":
# 实际应用中,这里会获取表单数据,进行验证,保存到数据库等操作
username = request.form.get('username')
password = request.form.get('password')
print(f"收到注册请求 - 用户名: {username}, 密码: {password}")
# 注册成功后可以重定向到成功页面或登录页面
return f"注册成功,欢迎用户: {username}!" # 简单示例响应
# else: # 对于未明确允许的请求方法,Flask 会自动返回 405 Method Not Allowed
# pass在 templates/another_file.html 文件中,我们将创建一个包含简单注册表单的页面。
<!-- templates/another_file.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>注册页面</title>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
h1 { color: #333; }
form { margin-top: 20px; padding: 20px; border: 1px solid #ccc; border-radius: 5px; }
label { display: block; margin-bottom: 5px; font-weight: bold; }
input[type="text"], input[type="password"] {
width: 100%;
padding: 8px;
margin-bottom: 10px;
border: 1px solid #ddd;
border-radius: 4px;
box-sizing: border-box; /* 确保内边距和边框不会增加元素总宽度 */
}
input[type="submit"] {
background-color: #28a745;
color: white;
padding: 10px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}
input[type="submit"]:hover {
background-color: #218838;
}
p a { color: #007bff; text-decoration: none; }
p a:hover { text-decoration: underline; }
</style>
</head>
<body>
<h1>用户注册</h1>
<p>请填写以下信息进行注册。</p>
<form action="/register" method="post">
<label for="username">用户名:</label>
<input type="text" id="username" name="username" required><br>
<label for="password">密码:</label>
<input type="password" id="password" name="password" required><br>
<input type="submit" value="提交注册">
</form>
<p><a href="/">返回首页</a></p>
</body>
</html>在这个注册页中,我们创建了一个 HTML 表单,其 action 属性同样指向 /register,method 属性设置为 post。这意味着当用户点击“提交注册”按钮时,浏览器会向 /register URL 发送一个 POST 请求,并将表单数据包含在请求体中。
在上述 /register 路由函数中,我们使用了 request.method 来区分 GET 和 POST 请求:
通过在 @app.route 装饰器中添加 methods=['GET', 'POST'],我们明确告诉 Flask 这个路由可以处理 GET 和 POST 两种请求。如果未指定 methods 参数,则默认只允许 GET 请求。
from flask import redirect, url_for
# ...
elif request.method == "POST":
# ... 处理数据 ...
return redirect(url_for('success_page')) # 假设有一个名为 'success_page' 的路由通过本教程,您已经掌握了在 Flask 应用中实现 HTML 页面之间导航的基本方法。理解 @app.route 和 render_template 的工作原理,以及如何处理不同 HTTP 请求方法,是构建任何 Flask Web 应用的关键。遵循良好的实践,您将能够构建出结构清晰、功能完善的多页面 Flask 应用。
以上就是Flask 应用中实现多 HTML 页面导航:从首页到注册页的路由实践的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号