Python Flask实现点击按钮跳转至自定义页面

Ryan
Ryan
发布时间:2026-10-14| 7人浏览过
原创

本文介绍如何利用Python Flask框架实现网页中按钮点击后跳转至自定义页面的功能。通过配置Flask路由、编写HTML模板及处理GET/POST请求,演示了从首页链接到表单页的完整流程。代码示例展示了@app.route装饰器的使用及render_template函数的调用,适用于希望掌握Flask基础页面交互的开发者参考。

Flask按钮跳转核心代码实现

核心实现代码如下:

文件名为_init_.py


from flask import Flask, request, url_for, redirect, render_template

app = Flask(__name__)

@app.route('/')
def index():
  return render_template('index.html')

@app.route('/cool_form', methods=['GET', 'POST'])
def cool_form():
  if request.method == 'POST':
    # do stuff when the form is submitted

    # redirect to end the POST handling
    # the redirect can be to the same route or somewhere else
    return redirect(url_for('index'))

  # show the form, it wasn't submitted
  return render_template('cool_form.html')

首页模板index.html的内容如下:


<!doctype html>
<html>
<body>
  <p><a href="{{ url_for('cool_form') }}" rel="external nofollow" >Check out this cool form!</a></p>
</body>
</html>

自定义表单页面cool_form.html的代码如下:


<!doctype html>
<html>
<body>
  <form method="post">
    <button type="submit">Do it!</button>
  </form>
</html>

页面运行效果与跳转演示

程序运行后的效果如下所示:

启动服务后访问5000端口,页面显示如图所示。点击页面上的按钮,即可跳转至自定义的/cool_form页面。

完整代码获取与扩展应用

相关完整代码托管于GitHub仓库:https://github.com/qingnvsue/flask,具体位于webbutton文件夹内。

在另一个实际应用场景中,程序实现了在Web页面点击“加法器”或“除法器”按钮后,分别跳转至对应功能页面的逻辑。

该场景的代码同样托管于GitHub仓库:https://github.com/qingnvsue/flask,具体位于add文件夹内。

以上即为本文的全部内容,希望这些内容能对各位的学习有所帮助,同时也欢迎大家继续支持本站。

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。