TypeError: tuple indices must be integers or slices, not str --python flask

I need to create a login and registration using python flask and Postgres. I have created registration so far and while trying to integrate the login api there arise and error. I have successfully inserted email, username, password, created into my database and while trying to validate using that email and password I cannot carry the login process. I want token in json format.

run.py

from app import app
if __name__ == '__main__':
    app.run(debug=True, port=5000)

login.py

from app import app, conn, bcrypt
from flask import request, jsonify
from flask_bcrypt import Bcrypt, check_password_hash
from datetime import datetime
import logging
from flask_jwt_extended import create_access_token

# registration api #################################################33


@app.route('/users/register', methods=['POST'])
def register():

    try:
        cur = conn.cursor()
        first_name = request.get_json()['first_name']
        last_name = request.get_json()['last_name']
        email = request.get_json()['email']
        password = bcrypt.generate_password_hash(
            request.get_json()['password']).decode('utf-8')
        created = datetime.utcnow()

        cur.execute("INSERT INTO admin.admin(first_name,last_name,email,password,created) VALUES('" +
                    str(first_name) + "','" +
                    str(last_name) + "','" +
                    str(email) + "','" +
                    str(password) + "','" +
                    str(created) + "')")
        conn.commit()
        result = {
            "first_name": first_name,
            "last_name": last_name,
            "email": email,
            "password": password,
            "created": created
        }
        return jsonify({"result": result})
    except Exception as e:
        conn.rollback()
        logging.error("db error:{}".format(e))

##########################LOGIN API#######################################


@app.route('/users/login', methods=['POST'])
def login():


        cur = conn.cursor()
        email = request.get_json()['email']
        password = request.get_json()['password']
        result = ""
        cur.execute("SELECT * FROM admin.admin WHERE email='" +
                    str(email) + "'")
        rv = cur.fetchone()

        if bcrypt.check_password_hash(rv['password'], password):

            access_token = create_access_token(identity={'first_name': rv['first_name'], 'last_name': rv['last_name'], 'email': rv['email']})
            result = jsonify({"token": access_token})
        else:
            result = jsonify({"error": "invalid username and password"})
            return result

app.py

from flask import Flask, jsonify, request, json
import psycopg2
from datetime import datetime
from flask_cors import CORS
from flask_bcrypt import Bcrypt
from flask_jwt_extended import JWTManager
from flask_jwt_extended import create_access_token


app = Flask(__name__)
conn = psycopg2.connect(host="localhost", database="practise",
                        user="postgres", password="dbA@pr3mium")
bcrypt = Bcrypt(app)
jwt = JWTManager(app)
CORS(app)

import login

requirements.txt

astroid==2.3.3
autopep8==1.5
bcrypt==3.1.7
cffi==1.14.0
click==7.1.1
colorama==0.4.3
Flask==1.1.1
Flask-Bcrypt==0.7.1
Flask-Cors==3.0.8
Flask-JWT-Extended==3.24.1
Flask-SQLAlchemy==2.4.1
isort==4.3.21
itsdangerous==1.1.0
Jinja2==2.11.1
lazy-object-proxy==1.4.3
MarkupSafe==1.1.1
mccabe==0.6.1
psycopg2==2.8.4
pycodestyle==2.5.0
pycparser==2.20
PyJWT==1.7.1
pylint==2.4.4
six==1.14.0
SQLAlchemy==1.3.15
Werkzeug==1.0.0
wrapt==1.11.2

error occured
127.0.0.1 - - [25/Mar/2020 20:19:56] "POST /users/login HTTP/1.1" 500 -
Traceback (most recent call last):
  File "C:\Users\sudeep\Desktop\example\venv\Lib\site-packages\flask\app.py", line 2463, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Users\sudeep\Desktop\example\venv\Lib\site-packages\flask\app.py", line 2449, in wsgi_app
    response = self.handle_exception(e)
  File "C:\Users\sudeep\Desktop\example\venv\Lib\site-packages\flask_cors\extension.py", line 161, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
  File "C:\Users\sudeep\Desktop\example\venv\Lib\site-packages\flask\app.py", line 1866, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\sudeep\Desktop\example\venv\Lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "C:\Users\sudeep\Desktop\example\venv\Lib\site-packages\flask\app.py", line 2446, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\sudeep\Desktop\example\venv\Lib\site-packages\flask\app.py", line 1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\sudeep\Desktop\example\venv\Lib\site-packages\flask_cors\extension.py", line 161, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
  File "C:\Users\sudeep\Desktop\example\venv\Lib\site-packages\flask\app.py", line 1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\sudeep\Desktop\example\venv\Lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "C:\Users\sudeep\Desktop\example\venv\Lib\site-packages\flask\app.py", line 1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\sudeep\Desktop\example\venv\Lib\site-packages\flask\app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Users\sudeep\Desktop\example\login.py", line 57, in login
    if bcrypt.check_password_hash(rv['password'], password):
TypeError: tuple indices must be integers or slices, not str

1 answer

  • answered 2020-03-25 17:59 above_c_level

    fetchone() returns a tuple, not a dictionary. So

    rv['password']
    

    does not work. You have to figure out the index position. For example, if the password is at the third position, change it to

    rv[2]