Python flask 表单详解

文章目录

  • [1 概述](#1 概述)
    • [1.1 request 对象](#1.1 request 对象)
  • [2 示例](#2 示例)
    • [2.1 目录结构](#2.1 目录结构)
    • [2.2 student.html](#2.2 student.html)
    • [2.3 result.html](#2.3 result.html)
    • [2.4 app.py](#2.4 app.py)

1 概述

1.1 request 对象

  • 作用:来自客户端网页的数据作为全局请求对象发送到服务器
  • request 对象的重要属性如下:
属性 解释
form 字典对象,包含表单的参数、值、键值对
args 解析查询字符串的内容,是问号(?)之后的 url 的一部分
cookies 字典对象,保存 cookie 的名称和值
files 与上传文件有关的数据
method 当前请求的方法,如:POST、GET

2 示例

  • 表单操作的示例,步骤如下
    • ① 访问浏览器,并在主页 student.html 中录入学生信息
    • ② 点击提交按钮,并将结果返回至 result.html 页面

2.1 目录结构

实现效果:

2.2 student.html

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>学生信息表</title>
</head>
<body>
<form action="/result" method="POST">
    <p>name <input type="text" name="name"/></p>
    <p>sex <input type="text" name="sex"/></p>
    <p>age <input type="text" name="age"/></p>
    <p><input type="submit" value="submit"/></p>
</form>
</body>
</html>

2.3 result.html

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>结果列表</title>
</head>
<body>
<table border="1" cellspacing="0" cellpadding="2">
    {% for key, value in result.items() %}
    <tr>
        <th> {{ key }}</th>
        <td> {{ value }}</td>
    </tr>
    {% endfor %}
</table>
</body>
</html>

2.4 app.py

python 复制代码
from flask import Flask, render_template, request

app = Flask(__name__)


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


@app.route('/result', methods=['POST', 'GET'])
def result():
    if request.method == 'POST':
        result = request.form
        return render_template("result.html", result=result)


if __name__ == '__main__':
    app.run(debug=True)
相关推荐
Mr.朱鹏16 小时前
【FastAPI 全栈实战 | 第2篇】Pydantic 数据校验与响应模型 —— 让 Bug 死在请求进来的那一刻
人工智能·python·fastapi
Xiangchu_16 小时前
安徽硅胶厂的转型困局:从家电到汽车,卡在哪
经验分享·python·阿里云·eclipse·汽车·制造
Edward1111111117 小时前
一AI名词
java·开发语言·数据库·学习
CTA终结者17 小时前
近期AI量化工具推荐,围绕最难推进的环节选择
人工智能·python
栈溢出了17 小时前
Redis repl_backlog 学习笔记
java·开发语言·redis·学习
谙忆17 小时前
Python 常用图像处理库速查:Pillow、OpenCV、rembg、pillow-simd 各擅长什么、怎么选
图像处理·python·pillow
urkay-17 小时前
Kotlin Flow分类
android·开发语言·kotlin
敲代码的猴先生17 小时前
论文分享 | TensorAbuse:通过滥用TensorFlow API将AI模型转化为恶意软件
人工智能·python·语言模型·tensorflow·论文笔记
言乐617 小时前
Python视频相对亮度检测
数据库·python·计算机视觉·小程序·音视频
Csvn17 小时前
Python 开发技巧 · logging 最佳实践 —— 告别 print,搭建工程级日志系统
后端·python