2

I have a Python code.

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)

And its html correspondante:

<!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>

I'm relatively new to Flask and Python in general. When I run the forms, they get displayed, but when I try to insert them into the database, I get this:

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

What exactly is causing it and how do I fix it?

halfer
  • 19,824
  • 17
  • 99
  • 186
Benjamin Safari
  • 89
  • 2
  • 11
  • Please read [Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers?](//meta.stackoverflow.com/q/326569) - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions. – halfer Sep 20 '18 at 19:42

2 Answers2

0

When posting to /post_data endpoint the browser recieves a redirection code, and then gets /add without posting any data, provoking a key error.

You are fetching form elements at the wrong place. You should do the database insertion logic inside /post_data and redirect to /add afterwards.

Diane M
  • 1,503
  • 1
  • 12
  • 23
  • It still is the right thing to do. I'm surprised you still get a key error. Perhaps it is failing for an other reason ? Did you restart the app ? You should also try to do things step by step by making your post correct before inserting to a database (it would also make your question simpler and get more responses). Check for example https://stackoverflow.com/questions/10434599/how-to-get-data-received-in-flask-request – Diane M Sep 21 '18 at 08:55
0

Here you are posting the form data to /post_data and redirect it to /add so the edited function will not be able to access the request object containing the form data. So just change the form action to /add to make it work correctly.

Suresh Kumar
  • 364
  • 3
  • 7
  • To make it working first you have to change the methods as method in `forms.html`. Then you have to add methods = ['POST'] to the `/add` route – Suresh Kumar Sep 21 '18 at 15:12