0

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!

3
  • Could you provide more of the code so we can get the bigger picture? Commented Feb 19, 2019 at 15:24
  • Hi Alex! Here you are codeshare.io/G8kVvA Thanks!!! Commented Feb 19, 2019 at 15:30
  • As I can see at your postman screen, you typed parameters of request, not json (body of the request). Commented Nov 28, 2019 at 14:09

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks shlomta1. But it isn the problem. I change the varaible outside the try clause and nothing. The anothers methods runs. For example to GET users. Take a look -> codeshare.io/G8kVvA Thanks!
0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.