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

时间:2018-09-20 18:43:22

标签: python oracle forms flask oracle11g

我有一个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">

        <!-- Latest compiled and minified JavaScript -->
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous">
        </script>
    <title>Base de dados</title>
</head>
<body>
    <form methods="POST" action="/post_data">
        <div class="col-lg-2">
            <div class="form-group">
                <label for="element-1" >Codigo:</label>
                <input id="cod_ed" name="cod_ed" type="text" class="form-control" placeholder="Codigo"/>

                <label for="element-2" >Nome:</label>
                <input id="nome_ed" name="nome_ed" type="text" class="form-control" placeholder="Nome"/>

                <label for="element-3" >Endereço:</label>
                <input id="endereco" name="endereco" type="text" class="form-control" placeholder="Endereço"/>

                <label for="element-4" >Telefone:</label>
                <input  id="telefone" name="telefone" type="text" class="form-control" placeholder="Telefone"/>

                <label for="element-5" >Cidade:</label>
                <input  id="cidade" name="cidade" type="text" class="form control" placeholder="Cidade"/>

                <input class="btn btn-info" type="submit" value="Enter">
                </div>
            </div>
        </div>
    </form>
</body>
</html>

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

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

究竟是什么原因导致的?我该如何解决?

2 个答案:

答案 0 :(得分:0)

在发布到/post_data端点时,浏览器会收到一个重定向代码,然后获取 /add而没有发布任何数据,从而引发键错误。

您在错误的位置获取表单元素。您应该在/post_data内部执行数据库插入逻辑,然后再重定向到/add

答案 1 :(得分:0)

在这里,您将表单数据发布到/post_data并将其重定向到/add,因此,已编辑的函数将无法访问包含表单数据的请求对象。因此,只需将表单操作更改为/add即可使其正常工作。