Flask - request.args.getlist - 只能读取一次?

如何解决Flask - request.args.getlist - 只能读取一次?

在我的 Flask 应用程序中,我使用如下参数重定向到另一个页面:

return redirect(url_for("edit.editFunction",plants=thisPlant))

然后,在另一个文件中,我正在用这些行读取该参数:

    # Get arguments from url_for in administration
    thisPlant = request.args.getlist("plants")
    print(thisPlant)

    # Get ID on edit plant
    plant_id = thisPlant[0]
    print(plant_id)

到目前为止,我的控制台返回的效果很好:

['1','aa','11','https://i.ibb.co/QNJnLR8/empty.png','1']
1

但是当我想在同一个文件上使用 post 方法时,我得到了这个:

    plant_id = thisPlant[0]
IndexError: list index out of range

怎么会这样?我应该读1 有人能发现我的错误吗?

这是我使用这个变量的完整文件:

import sqlite3
import traceback
import sys
import re
import os

from flask import Blueprint,render_template,redirect,session,request,flash,get_flashed_messages
from application import getUserName,getUserPicture,login_required,confirmed_required,getUserRole,role_required,uploadPicture
from werkzeug.utils import secure_filename

# Set Blueprints
edit = Blueprint('edit',__name__,)

@edit.route("/edit",methods=["GET","POST"])
@login_required
@confirmed_required
@role_required
def editFunction():    

    # Force flash() to get the messages on the same page as the redirect.
    get_flashed_messages()

    if request.method == "POST":

        # Get variables
        plant_id = request.form.get("plant_id")
        name = request.form.get("name")
        stock = request.form.get("stock")
        price = request.form.get("price")
        description = request.form.get("description")

        # Ensure the plant name was submitted
        if not name:
            flash("must provide plant name")
            return redirect("/edit")

        # Ensure the plant name fits server-side
        if not re.search("^[a-zA-Z0-9]{1,50}$",name):
            flash("Invalid plant name")
            return redirect("/edit")

        # Ensure the plant stock was submitted
        if not stock:
            flash("must provide plant stock")
            return redirect("/edit")

        # Ensure the plant stock fits server-side
        if not re.search("^[0-9]+$",stock):
            flash("Invalid plant stock")
            return redirect("/edit")

        # Ensure the plant price was submitted
        if not stock:
            flash("must provide plant price")
            return redirect("/edit")

        # Ensure the plant price fits server-side
        if not re.search("^[0-9]+$",stock):
            flash("Invalid plant price")
            return redirect("/edit")

        # Ensure the plant description was submitted
        if not description:
            flash("must provide plant description")
            return redirect("/edit")

        # Ensure the plant description fits server-side
        if not re.search("^(?!;).+",description):
            flash("Invalid plant description")
            return redirect("/edit")

        # Check show bool status
        show = "show" in request.form


        # Update plant name,stock,price,description and show status into the table
        try:

            sqliteConnection = sqlite3.connect("database.db")
            cursor = sqliteConnection.cursor()

            cursor.execute("UPDATE plants SET name=:name,stock=:stock,price=:price,description=:description,show=:show WHERE id=:plant_id;",{"name": name,"stock": stock,"price": price,"description": description,"show": show,"plant_id": plant_id})
            sqliteConnection.commit()

            cursor.close()

        except sqlite3.Error as error:
        
            print("Failed to read data from sqlite table",error)
            print("Exception class is: ",error.__class__)
            print("Exception is",error.args)

            print('Printing detailed SQLite exception traceback: ')
            exc_type,exc_value,exc_tb = sys.exc_info()
            print(traceback.format_exception(exc_type,exc_tb))

        finally:

            if (sqliteConnection):
                sqliteConnection.close()

        # Save,upload and delete picture file
        file = request.files["picture"]

        if file and file.filename:

            filename = secure_filename(file.filename)
            file.save(os.path.join("./static",filename))
            upload = uploadPicture("./static/" + filename)
            os.remove("./static/" + filename)

            # Update database with new image url 
            try:

                sqliteConnection = sqlite3.connect("database.db")
                cursor = sqliteConnection.cursor()
                
                cursor.execute("UPDATE plants SET picture=:picture WHERE name=:name;",{"picture": upload,"name": name})
                sqliteConnection.commit()

                cursor.close()

            except sqlite3.Error as error:
            
                print("Failed to read data from sqlite table",error)
                print("Exception class is: ",error.__class__)
                print("Exception is",error.args)

                print('Printing detailed SQLite exception traceback: ')
                exc_type,exc_tb = sys.exc_info()
                print(traceback.format_exception(exc_type,exc_tb))

            finally:

                if (sqliteConnection):
                    sqliteConnection.close()

        flash("Plant edited")
        return redirect("/administration")


    else:
        # Get arguments from url_for in administration
        thisPlant = request.args.getlist("plants")
    
        return render_template("edit.html",name=getUserName(),picture=getUserPicture(),role=getUserRole(),plants=thisPlant)

这是完整的控制台输出:

127.0.0.1 - - [05/Jan/2021 22:20:44] "GET /administration HTTP/1.1" 200 -
127.0.0.1 - - [05/Jan/2021 22:20:44] "GET /static/styles.css HTTP/1.1" 200 -
127.0.0.1 - - [05/Jan/2021 22:20:45] "POST /administration HTTP/1.1" 302 -
['1','1']
1
127.0.0.1 - - [05/Jan/2021 22:20:45] "GET /edit?plants=1&plants=aa&plants=11&plants=11&plants=https%3A%2F%2Fi.ibb.co%2FQNJnLR8%2Fempty.png&plants=aa&plants=1 HTTP/1.1" 200 -
127.0.0.1 - - [05/Jan/2021 22:20:45] "GET /static/styles.css HTTP/1.1" 200 -
[]
[2021-01-05 22:20:53,655] ERROR in app: Exception on /edit [POST]
Traceback (most recent call last):
  File "/home/benoit/Documents/CrazyPlantCrew/venv/lib/python3.8/site-packages/flask/app.py",line 2447,in wsgi_app
    response = self.full_dispatch_request()
  File "/home/benoit/Documents/CrazyPlantCrew/venv/lib/python3.8/site-packages/flask/app.py",line 1952,in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/benoit/Documents/CrazyPlantCrew/venv/lib/python3.8/site-packages/flask/app.py",line 1821,in handle_user_exception
    reraise(exc_type,tb)
  File "/home/benoit/Documents/CrazyPlantCrew/venv/lib/python3.8/site-packages/flask/_compat.py",line 39,in reraise
    raise value
  File "/home/benoit/Documents/CrazyPlantCrew/venv/lib/python3.8/site-packages/flask/app.py",line 1950,in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/benoit/Documents/CrazyPlantCrew/venv/lib/python3.8/site-packages/flask/app.py",line 1936,in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/benoit/Documents/CrazyPlantCrew/application.py",line 94,in decorated_function
    return f(*args,**kwargs)
  File "/home/benoit/Documents/CrazyPlantCrew/application.py",line 109,line 124,**kwargs)
  File "/home/benoit/Documents/CrazyPlantCrew/routes/edit.py",line 28,in editFunction
    plant_id = thisPlant[0]
IndexError: list index out of range
127.0.0.1 - - [05/Jan/2021 22:20:53] "POST /edit HTTP/1.1" 500 -
Error on request:
Traceback (most recent call last):
  File "/home/benoit/Documents/CrazyPlantCrew/venv/lib/python3.8/site-packages/flask/app.py",in editFunction
    plant_id = thisPlant[0]
IndexError: list index out of range

During handling of the above exception,another exception occurred:

Traceback (most recent call last):
  File "/home/benoit/Documents/CrazyPlantCrew/venv/lib/python3.8/site-packages/werkzeug/serving.py",line 304,in run_wsgi
    execute(self.server.app)
  File "/home/benoit/Documents/CrazyPlantCrew/venv/lib/python3.8/site-packages/werkzeug/serving.py",line 292,in execute
    application_iter = app(environ,start_response)
  File "/home/benoit/Documents/CrazyPlantCrew/venv/lib/python3.8/site-packages/flask/app.py",line 2464,in __call__
    return self.wsgi_app(environ,line 2450,in wsgi_app
    response = self.handle_exception(e)
  File "/home/benoit/Documents/CrazyPlantCrew/venv/lib/python3.8/site-packages/flask/app.py",line 1881,in handle_exception
    return self.finalize_request(server_error,from_error_handler=True)
  File "/home/benoit/Documents/CrazyPlantCrew/venv/lib/python3.8/site-packages/flask/app.py",line 1968,in finalize_request
    response = self.make_response(rv)
  File "/home/benoit/Documents/CrazyPlantCrew/venv/lib/python3.8/site-packages/flask/app.py",line 2097,in make_response
    raise TypeError(
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.

编辑:添加表单

{% extends "layout.html" %}

{% block title %}
    Edit
{% endblock %}

{% block navigation %}
    {% if role == "admin" %}
        <li><a href="/administration">Administration</a></li>
        <li><a href="/communication">Update blog</a></li>
        <li><a href="/newsletter">Send newsletter</a></li>
    {% endif %}
{% endblock %}

{% block main %}
        <form action="/edit" method="post" enctype="multipart/form-data">
            <div>
                <input type='hidden' name='plant_id' value='{{ plants[0]}}'>
            </div>
            <div>
                <input id="name" autocomplete="off" autofocus class="form-control" name="name" placeholder="Name" type="text" value="{{ plants[1] }}">
            </div>
            <br>
            <div>
                <input id="stock" autocomplete="off" autofocus class="form-control" name="stock" placeholder="Stock" type="number" min="0" value="{{ plants[2] }}">
            </div>
            <br>
            <div>
                <input id="price" autocomplete="off" autofocus class="form-control" name="price" placeholder="Price" type="number" min="0" value="{{ plants[3] }}">
            </div>
            <br>
            <div>
                <textarea id="description" autocomplete="off" autofocus class="form-control" name="description" placeholder=" Description" type="text" cols="100" rows="10">{{ plants[5] }}</textarea>
            </div>
            <br>
            <div>
                <input type="file" id="picture" name="picture">
            </div>
            <br>
            <div>
                <input type="checkbox" id="show" name="show" value="show" checked="{{ plants[6] }}">
                <label for="show"> Show?</label><br>
            </div>
            <br>
            <div>
                <button id="submit" type="submit" name="submit" value="submit">Save.</button>
            </div>
            <br>
            <div>
                <a href="/administration">Back</a>
            </div>
        </form>
{% endblock %}

EDIT2:向我的代码添加解决方案 - 非常感谢 v25!

解决方法

如果我没看错的话...

request.args.getlist 仅抓取作为 URL 参数发布的数据,因此在 POST 请求期间尝试访问 KeyError 时会获取 plants[0]。请注意,在服务器日志中,POST 请求期间的 print(thisPlant) 给出了一个空列表:[]

似乎您只需要重新构造该路由,因此有问题的行仅在 GET 请求中执行。

类似于:


def editFunction():    

    # Force flash() to get the messages on the same page as the redirect.
    get_flashed_messages()

    if request.method = 'GET':
        # Get arguments from url_for in administration
        thisPlant = request.args.getlist("plants")
        print(thisPlant)

        # Get ID on edit plant
        plant_id = thisPlant[0]
        print(plant_id)

        # Do return here,rather than in 'else' statement at bottom of file
        return render_template("edit.html",name=getUserName(),picture=getUserPicture(),role=getUserRole(),plants=thisPlant)

    elif request.method == "POST":

        # code to handle POST Request

        # ...

        flash("Plant edited")
        return redirect("/administration")

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res