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)
相关推荐
孟健6 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞8 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽10 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程15 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪15 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook15 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python