myrdstom
myrdstom

Reputation: 306

row = result.fetchone() AttributeError: 'NoneType' object has no attribute 'fetchone'

I have a python script that is supposed to 'GET' information from a postgres database

create_table.py

from flask import request
from flask_restful import Resource

import psycopg2

class single_user_Request(Resource):
   def get(self, username):
      connection = psycopg2.connect("dbname = 'tracker' "
                                  "user = 'postgres' "
                                  "password='rasengan1408' "
                                  "host = 'localhost' "
                                  "port='5432'")
      cursor = connection.cursor()

      query = "SELECT * FROM users WHERE username=%s"
      result = cursor.execute(query, (username,))
      row = result.fetchone()
      connection.close()
      if row:
          return {'req_id':row[0], 'username':row[1], 'equipment_name': row[2], 'requesttype':row[3], 'description': row[4], 'status':row[5]}
      return {'message':'request not found'}, 404

init.py

from flask import Flask
from flask_restful import Api
from app.api.v1.requests import single_user_Request


def create_app():
    app = Flask(__name__)
    app.secret_key = 'GciOiJIUzI1NiJ9.eyJleHAiOj'
    api = Api(app)


    api.add_resource(single_user_Request, '/api/v1/userrequests/<string:username>')

return app

run.py

from app.api import create_app

app = create_app()

app.run(debug=True)

After running the script

AttributeError: 'NoneType' object has no attribute 'fetchone'

I'm struggling to see why fetchone would be a nonetype object if the database has data

Upvotes: 4

Views: 7668

Answers (2)

Kaunda
Kaunda

Reputation: 77

In my case, the code in the screenshot below worked perfectly on my machine (laptop).

enter image description here

But when I tried to access the same route (all_predictions) on another machine, the application crashed with an error message that says:

AttributeError: 'NoneType' object has no attribute 'fetchone'

After wasting half a day, I realized in my case, the error was a result of the SqlAlchemy version.

The version I had on my laptop was

SQLAlchemy==1.3.8

And the version on the new machine was

SQLAlchemy==1.4.35

So I uninstalled the above version by running:

pip uninstall SQLAlchemy

and then installed the specific 1.3.8 version by running:

pip install SQLAlchemy==1.3.8

Boom! the error disappeared, and everything worked fine.

Upvotes: 0

Peeyush
Peeyush

Reputation: 726

cursor.execute doesn't return anything, you need to change you code like this

query = "SELECT * FROM users WHERE username=%s"
cursor.execute(query, (username,))
row = cursor.fetchone()

Upvotes: 5

Related Questions