如何读取Flask函数中隐藏的表单数据[重复]

2024-06-28

我正在为 Flask 应用程序做一个作业,该应用程序的函数根据 index.html 页面上表单中隐藏字段的值执行不同的操作。我只有两条路线:“/”(index.html)和“/process”(对index.html执行操作)。

当我在 Flask 中运行它(virtualenv 中的 python server.py),并单击 index.html 上的“赚钱”按钮时,出现以下错误:

“类型错误 类型错误:“ImmutableMultiDict”对象不可调用”

有人可以告诉我如何从隐藏输入中获取所需的值吗?

server.py 的内容

import datetime
import random
from flask import Flask, render_template, redirect, request, session

app = Flask(__name__)
app.secret_key = 'fooBarBaz'

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

@app.route('/process', methods=['GET','POST'])
def process():
    if request.method == 'POST':
        target = request.form('name')
        if target == 'clothing':
            new_money = random.randrange(10, 21)
            session['balance'] += new_money
            timestamp = datetime.datetime.now()
            session['register'] += ("Received" + new_money + " dollars at " + timestamp.strftime("%Y/%m/%d %I:%M %p")) 
        return render_template('index.html')

app.run(debug=True)

index.html 的内容:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div container>
        <div class='balance'>
            <p>Your balance:  {{ session['balance'] }}</p>
        </div>
        <div class="shops">
            <div class="clothing">
                <h2>Clothing Store</h2>
                <p>(earns 10 - 20 dollars)</p>
                <form action="/process" method="post">
                    <input type="hidden" name="clothing">
                    <input type="submit" value="Make Money!">
                </form>
            </div> 
        </div> 
        <div class="register">
            <h4>Receipt Tape</h4>
            <p>{{ session['register'] }}</p>
        </div>
    </div>
</body>
</html>

表单应如下所示,并为隐藏输入定义一个值:

<form action="/process" method="post">
    <input type="hidden" name="clothing" value="clothing">
    <input type="submit" value="Make Money!">
</form>

在不改变太多逻辑的情况下,寄存器部分可以接受 html 标签来渲染换行符

<p>{{ session['register']|safe }}</p>

然后,通过最小的更改,您就可以解决视图中遇到的一些问题。为了避免错误sessionkey 未声明,最好的方法是使用该方法get with 0, or ""而不是None未找到密钥时返回:

@app.route('/process', methods=['GET','POST'])
def process():

    if request.method == 'POST':
        target = request.form.get('clothing')
        if target == 'clothing':
            new_money = random.randrange(10, 21)
            session['balance'] = session.get('balance',0) + new_money
            timestamp = datetime.datetime.now()
            session['register'] = "{}<br>Received {} dollars at {}".format(
                session.get('register',''),
                new_money,
                timestamp.strftime("%Y/%m/%d %I:%M %p"))
        return render_template('index.html')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何读取Flask函数中隐藏的表单数据[重复] 的相关文章

随机推荐

  • 在 JLayeredPane 中使用 GridBagLayout

    我试图在 JPanel 的右上角有一个小的浮动 小部件 它是一个固定大小的组件 想象一下谷歌地图视图中的指南针 如果有帮助的话 我意识到 JLayeredPane 只对所有层使用一个布局管理器 因此认为使用 GBL 是成功的 使右上角的 1
  • 如何将进程窗口置于前面?

    我在 Form1 中有这个按钮点击代码 private void DriverVerifier Click object sender EventArgs e if MessageBox Show Are you Sure you want
  • 如何在 .css 文件中使用 php 变量

    我有一个名为test css我想用它 var var is at test php test css附于test php 我的结构是这样的 test php 这是 test css test css
  • dplyr 通过评估查找单元格值来改变特定列

    我已经使用定额 符号和求值探索了各种选项 但我似乎无法获得正确的语法 这是一个示例数据框 data frame A letters 1 4 B letters 26 23 C letters c 1 3 5 7 D letters c 2
  • 如何在 Common Lisp 中可移植地解析命令行参数和标志?

    我想获取并解析 Common Lisp 中的命令行参数 以便例如myscript a 1 b 2将使我能够获得价值观 并且myscript xyz也会起作用 我怎样才能做到可移植 在编译器之间 你可以试试unix options http
  • 如何为 3.x 到 2.x IPC 设置 Python 多处理 pickle 协议

    我正在尝试在同一台机器上的两个 Python 进程 Py2 中的侦听器和 Py3 中的客户端 之间建立真正基本的字符串消息 IPC 不需要对象或任何类似的东西 这不能开箱即用 因为 Py3 MP 默认使用 Pickle 协议 3 而 Py2
  • 如何在使用 Apache 2 的 Windows 上忽略 Perl shebang?

    我已经在我的 Windows 机器上设置了本地 Perl Web 环境 我正在开发的应用程序最初来自 Linux 服务器 因此源代码的 shebang pl文件看起来像这样 usr bin perl 这会导致我的 Windows 开发机器上
  • 有条件的正则表达式替换

    使用Python 您可以在替换文本之前检查组是否为空 Example user John Marshal gt user br strong Jonh Marshal strong John Marshal gt strong Jonh M
  • tkinter.mainloop 函数的 n 参数是什么?

    A n参数可以被赋予tkinter mainloop功能 help tkinter Tk mainloop gt gt gt gt mainloop self n 0 What is n here Call the mainloop of
  • 无法打开项目...无法打开,因为无法解析项目文件

    我已经工作了一段时间来创建 iPhone 应用程序 今天 当我的电池电量不足时 我正在工作并不断保存我的源文件 然后电源就断了 现在 当我重新插入计算机并且电源正常时 我尝试打开我的项目文件 但出现错误 无法打开项目 项目 无法打开 因为无
  • Cython、CMake和setup.py、python在一个子目录下编译两次

    我正在尝试按照以下结构与 Cython 绑定一起构建 C 库https bloerg net 2012 11 10 cmake and distutils html https bloerg net 2012 11 10 cmake and
  • 在 BASH 中按字节读取文件

    我需要读取指定文件的第一个字节 然后读取第二个字节 第三个字节 依此类推 我怎样才能在 BASH 上做到这一点 P S 我需要获取这个字节的十六进制 完全重写 2019 年 9 月 比以前的版本更短更简单 速度更快 但没那么快 Yes ba
  • Numpy 矩阵到 tkinter 画布

    如何将 Numpy 矩阵作为位图显示到 Tkinter 画布中 更准确地说 如何填写PhotoImage来自矩阵的内容 photo ImageTk PhotoImage self canvas create image 0 0 image
  • 改变了 (un)serialize() 的行为?

    编辑 问题是现在已记录的 php 错误 https bugs php net bug php id 71617 https bugs php net bug php id 71617感谢您找到那个 Danack 我刚刚将应用程序从 PHPH
  • Shapeless 中 TypeClass 特征的 emptyCoproduct 和 coproduct 方法的用途是什么

    我并不完全清楚这样做的目的是什么emptyCoProduct and coproduct的方法TypeClass无形中的特质 什么时候会使用TypeClass特质而不是ProductTypeClass 这两种方法的实施方式有哪些示例 假设我
  • 使用php从图像中获取第一个像素

    我正在尝试获取图像的第一个像素 最好是最左上角或最右上角的一个像素 我看到了这个问题 它有最接近我的问题的答案 获取图像颜色 https stackoverflow com questions 1746530 get image color
  • 在 AngularJs 中设置动态作用域变量 -scope.

    我有一根绳子 是从routeParam或指令属性或其他什么 我想基于此在范围上创建一个变量 所以 scope
  • 如何使用Caliper进行基准测试?

    我试图弄清楚如何使用 Caliper 在 Eclipse 中进行基准测试 但一无所获 我尝试按照此处找到的 26 分钟教程进行操作 https code google com p caliper https code google com
  • 表示区间或范围? [关闭]

    Closed 这个问题是基于意见的 help closed questions 目前不接受答案 一般来说 每当您表示任何类型的范围时 您都可以选择为范围的开始和结束选择哪些类型的值 例如 如果您想要一个包含整数 1 2 3 4 5 的范围
  • 如何读取Flask函数中隐藏的表单数据[重复]

    这个问题在这里已经有答案了 我正在为 Flask 应用程序做一个作业 该应用程序的函数根据 index html 页面上表单中隐藏字段的值执行不同的操作 我只有两条路线 index html 和 process 对index html执行操