safernandez666
safernandez666

Reputation: 117

Python Flask API Restful

How Are you? I am play, with Python + Flask + MySQL to create a API. But I have some errors! With the connection. Here is the code of the Entry Point.

@app.route('/add', methods=['POST'])
def add_user():
    try:
        _json = request.json
        _name = _json['name']
        _email = _json['email']
        _password = _json['pwd']
        # validate the received values
        if _name and _email and _password and request.method == 'POST':
            #do not save password as a plain text
            _hashed_password = generate_password_hash(_password)
            # save edits
            sql = "INSERT INTO user(user_name, user_email, user_password) VALUES(%s, %s, %s)"
            data = (_name, _email, _hashed_password,)
            conn = mysql.connect()
            cursor = conn.cursor()
            cursor.execute(sql, data)
            conn.commit()
            resp = jsonify('User added successfully!')
            resp.status_code = 200
            return resp
        else:
            return not_found()
    except Exception as e:
        print(e)
    finally:
        cursor.close() 
        conn.close()

enter image description here

And here the error

enter image description here

I'm installed all the dependencies, but...I dont know. I connected the cursor, previosly, but nothing.

Can you help me? Thanks!

Upvotes: 0

Views: 287

Answers (3)

Serg Kram
Serg Kram

Reputation: 31

If you catch an exception before you define a cursor variable -> you cannot close the cursor because you interpreter doesn't know about it. I think the best way is to remove finally block and move

cursor.close() 
conn.close()

to the try block after conn.commit(). With that approach you can avoid error that you received.

P.S. It's not a good practice to catch errors with except Exception as e: because it impossible to understand what have been failed. It is better to define what errors you could face with and use the specific exceptions.

Upvotes: 0

akrantz01
akrantz01

Reputation: 648

So what's happening is that your try...catch is being triggered before the cursor is being made. If you look at your log, two lines above the beginning of the traceback it says:

'NoneType' object is not subscriptable

This is referring to request.json not being defined. It is not defined because you are not sending your request with JSON. Instead you are sending it with query parameters. To fix this you can either use request.args or add argument checks.

You should also change the finally clause to check whether cursor and conn are defined.

@app.route('/add', methods=['POST'])
def add_user():
    # Placeholder values
    conn = None
    cursor = None
    try:
        # This checks the body so you won't get an error thrown
        if request.json.get("name") is None or request.json.get("email") is None or request.json.get("pwd") is None:
            return "invalid body"
        _json = request.json
        _name = _json['name']
        _email = _json['email']
        _password = _json['pwd']
        # validate the received values
        if _name and _email and _password and request.method == 'POST':
            #do not save password as a plain text
            _hashed_password = generate_password_hash(_password)
            # save edits
            sql = "INSERT INTO tbl_user(user_name, user_email, user_password) VALUES(%s, %s, %s)"
            data = (_name, _email, _hashed_password,)
            conn = mysql.connect()
            cursor = conn.cursor()
            cursor.execute(sql, data)
            conn.commit()
            resp = jsonify('User added successfully!')
            resp.status_code = 200
            return resp
        else:
            return not_found()
    except Exception as e:
        print(e)
    finally:
        # Check if defined
        if cursor is not None:
            cursor.close() 
        if conn is not None:
            conn.close()

To send a JSON request in Postman, go to the body tab and set the type to Raw and then on the dropdown, change it from Text to JSON (application/json).

Postman result

Upvotes: 0

shlomta1
shlomta1

Reputation: 148

The cursor variable defined in your try clause and being used in your finally clause. You probably getting exception before cursor being defined (I assume when you trying to create the connection to mysql) and therefore you receiving this error.

Upvotes: 1

Related Questions