[我正在尝试使用PyMySQL设计一个基本的CRUD应用程序并得到一个'KEY ERROR'

问题描述 投票:0回答:1

以下是我在运行此app.py文件时在浏览器上遇到的HTML错误:

enter werkzeug.exceptions.BadRequestKeyError
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'hst_address' here

#app.py文件中的我的应用程序代码:

import pymysql.cursors
from flask import Flask
from flask import render_template, request, redirect, url_for, flash, session
from config import Config
import os


app = Flask(__name__)
app.secret_key = "super secret key"


@app.route("/")
def index():
    userId = verifySessionId()
    print("User id[" + str(userId) + "]")
    return render_template("index.html")


@app.route("/home")
def home():
    return render_template("home.html", home =True)

connection = pymysql.connect(host='localhost',
                             user='root',
                             password='',
                             db='F196083B',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)


@app.route('/insert/hospital', methods = ['POST'])
def insert_hospital():

    if request.method == "POST":

        hid = int(request.form['hid'])
        hname = request.form['hname']
        hst_address = request.form['dress']
        hst_city = request.form['hst_city']
        hstate = request.form['hstate']
        hzip = int(request.form['hzip'])
        flash("Data Inserted Successfully!", "success")

        cur = connection.cursor()
        cursor.execute("INSERT INTO patients (hid,hname,hst_address,hst_city,hstate,hzip) VALUES (%s, %s, %s,%s,%s,%s)", (hid,hname,hst_address,hst_city,hstate,hzip))
        # cur.execute("INSERT INTO hospital(hid, hname,hst_address,hst_city,hstate,hzip) values (%s, %s, %s, %s, %s, %s)",(hid, hname, hst_address, hst_city, hstate, hzip))
        connection.commit()
        return redirect("/hospital")

@app.route('/update/hospital', methods = ['GET', 'POST'])
def update_hospital():
    print("hi")
    if request.method == "POST":
        for key in request.form.keys():
            print(key)
        flash("Data Updated Successfully!", "success")
        hid = int(request.form['hid'])
        hname = request.form['hname']
        hst_address = request.form['hst_address']
        hst_city = request.form['hst_city']
        hstate = request.form['hstate']
        hzip = int(request.form['hzip'])

        cursor = connection.cursor()

        cur.execute("""
        UPDATE hospital 
        SET hname=%s,hst_address=%s,hst_city=%s,hstate=%s,hzip=%s 
        WHERE hid = %s
        """,(hname, hst_address, hst_city, hstate, hzip, hid))

        connection.commit()
    else:
        return redirect("/hospital")


@app.route('/delete/<int:row_id>', methods = ['GET','POST'])
def delete_hospital(row_id):
    cursor = connection.cursor()
    cursor.execute("DELETE FROM hospital where hid = %s", (row_id,))
    connection.commit()
    flash("Record Deleted Successfully!", "success")
    return redirect(url_for("hospital"))

@app.route("/patients")
def patient():
    sql = "SELECT * from `patient`;"
    result = {}
    with connection.cursor() as cursor:
        cursor.execute(sql)
        result = cursor.fetchall()
        record = cursor.fetchone()

    return render_template("patients.html", patient = result)


if __name__ == "__main__":

    app.run()

{% include 'header.html' %}
<div class="row">
  <div class="col md-12">
    <h2 class="mb-4">Hospital Details:
    </h2>
    <a href="{{ url_for('.add_hospital_view') }}" class="btn btn-sm btn-secondary">Add Hospital</a>
    <p>
      {% with messages = get_flashed_messages() %}
      {% if messages %}
      <ul class=flashes>
        {% for message in messages %}
        <li>{{ message }}</li>
        {% endfor %}
      </ul>
      {% endif %}
      {% endwith %}
    </p>
    {{ table }}
    <table class="table table-striped text-center">
      <thead>
        <tr>
          <th>Id</th>
          <th>Name</th>
          <th>Address</th>
          <th>City</th>
          <th>State</th>
          <th>Zip</th>
          <th>Edit</th>
          <th>Delete</th>
        </tr>
      </thead>
      <tbody>
        {% for row in hospital %}

        <tr>
          <td>{{row.hid}}</td>
          <td>{{row.hname}}</td>
          <td>{{row.hst_address}}</td>
          <td>{{row.hst_city}}</td>
          <td>{{row.hstate}}</td>
          <td>{{row.hzip}}</td>
          <td>
            <a href="{{ url_for('edit_view', row_id = row.hid) }}" class="btn btn-sm btn-secondary"> Edit</a>

          </td>
          <td>
            <a href="{{ url_for('delete_hospital', row_id = row.hid) }}" class="btn btn-sm btn-secondary"> Delete</a>

          </td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
  </div>
</div>
{% include 'footer.html'%}

到处都会将此错误密钥作为正确的密钥值“ hst-address”提供,但仍在我的控制台中,我将密钥显示为(使用app.py文件中的打印语句):

hi
hid
hname
hst_addrress # Which is wrong it should be displayed as **'address'**
hst_city
hstate
hzip
id

在我的代码中,包括数据库在内的每个地方,地址列的密钥都以'hst_address'的形式提供。我无法找到它,确切地说是从哪里得到这个关键错误。

html flask python-3.7
1个回答
0
投票
Werkzeug调试器指出您有一个'KeyError'。

此异常在您访问request.form字典时引发。此KeyError表示字典中没有这样的“键-值”对,这意味着客户端未在POST请求的有效负载中提供此字段。

问题的来源很可能是客户端

请查看您的客户端,在其中启动这些POST请求,并确保提供hst_addrress键值对。

如果使用表单,则可能在输入中缺少名称道具

<input type="text" name="hst_addrress"/>

如何在Flask视图中处理KeyError

from flask import abort from http import HTTPStatus @app.route('/update/hospital', methods = ['GET', 'POST']) def update_hospital(): print("hi") if request.method == "POST": for key in request.form.keys(): print(key) try: hid = int(request.form['hid']) hname = request.form['hname'] hst_address = request.form['hst_address'] hst_city = request.form['hst_city'] hstate = request.form['hstate'] hzip = int(request.form['hzip']) except KeyError: abort(HTTPStatus.BAD_REQUEST) cursor = connection.cursor() cur.execute(""" UPDATE hospital SET hname=%s,hst_address=%s,hst_city=%s,hstate=%s,hzip=%s WHERE hid = %s """,(hname, hst_address, hst_city, hstate, hzip, hid)) connection.commit() flash("Data Updated Successfully!", "success") # Makes more sense here else: return redirect("/hospital")

© www.soinside.com 2019 - 2024. All rights reserved.