将数据从 Python Flask 中的表单插入 Oracle 数据库

我有一个 Python 代码。


import cx_Oracle

import re

from flask import Flask, render_template, request, url_for, redirect


app = Flask(__name__)


app.config['SECRET_KEY'] = 'd369342136ecd032f8b4a930b6bb2e0e'


@app.route('/add')

def edited():

    connect = cx_Oracle.connect("********", "********", "******/XE")

    cursor = connect.cursor()


    cod_ed = request.form['cod_ed']

    nome_ed = request.form['nome_ed']

    endereco = request.form['endereco']

    telefone = request.form['telefone']

    cidade = request.form['cidade']

    execute = """INSERT INTO editor VALUES

            (:cod_ed, :nome_ed, :endereco, :telefone, :cidade)"""

    cursor.execute(execute, {'cod_ed':cod_ed, 'nome_ed':nome_ed, 'endereco':endereco, 'telefone':telefone, 'cidade':cidade})

    connect.commit()


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

def add_data():

    return render_template('forms.html')



@app.route('/post_data', methods=['GET','POST'])

def post_data():

    return redirect(url_for('edited'))


if __name__ == "__main__":

    app.run(host = 'localhost', port = 8000, debug=True)

和它的 html 通讯员:


<!DOCTYPE html>

<html>

<head>

    <!-- Latest compiled and minified CSS -->

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">


        <!-- Optional theme -->

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">


总的来说,我对 Flask 和 Python 比较陌生。当我运行表单时,它们会显示出来,但是当我尝试将它们插入数据库时,我得到了这个:


werkzeug.exceptions.HTTPException.wrap.<locals>.newcls: 400 Bad Request: KeyError: 'cod_ed'

究竟是什么原因造成的,我该如何解决?


炎炎设计
浏览 84回答 2
2回答

缥缈止盈

在这里,您将表单数据发布到/post_data并将其重定向到,/add因此已编辑的函数将无法访问包含表单数据的请求对象。所以只需将表单操作更改/add为使其正常工作。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python