Click here to Skip to main content
15,867,568 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
-2


I am working with mongodb and python flask. Every time I run flask  I receive this error on the local host and the terminal


query = db.Data.find(upsert=True)
AttributeError: 'NoneType' object has no attribute 'Data'

What I have tried:

<pre>app = Flask(__name__)

app.config['MONGO_URI'] = 'mongodb://****/****@cluster0-shard-00-00.i5hec.mongodb.net:27017,cluster0-shard-00-01.i5hec.mongodb.net:27017,cluster0-shard-00-02.i5hec.mongodb.net:27017/?ssl=true&replicaSet=atlas-oxpqgz-shard-0&authSource=admin&retryWrites=true&w=majority'
app.config['MONGO_DBNAME'] = 'Apitest1'

mongo = PyMongo(app)
db = mongo.db
if __name__ == '__main__':
    app.run(debug=True ,port=8080,use_reloader=False)

@app.route('/find', methods=['GET'])
def findAll():
   # db.Data.upsert()
    query = db.Data.find(upsert=True)
    output = {}
    i = 0
    for x in query:
        output[i] = x
        output[i].pop('_id')
        i += 1
    return jsonify(output)

@app.route('/insert-one/<name>/<id>/', methods=['GET'])
def insertOne(name, id):
   # db.Data.upsert()
    queryObject = {
        'Name': name,
        'ID': id
    }
    query = db.Data.insert_one(queryObject, upsert=True)
    return "Query inserted...!!!"
Posted
Updated 15-Aug-22 21:48pm

1 solution

You need a method to get the database reference, the db variable does not exist in the functions you are using. See Welcome to Flask — Flask Documentation (2.1.x)[^] for details of how to do it correctly.
 
Share this answer
 
Comments
Prathmesh Upadhyay 16-Aug-22 4:00am    
i added this

def get_db():
"""
Configuration method to return db instance
"""
db = getattr(g, current_app.config['MONGO_DBNAME'])

if db is None:
db = g._database = PyMongo(current_app).db

return db



db = LocalProxy(get_db)


but now i get this error:
File "C:\Users\CucumisSativus\PycharmProjects\api\application.py", line 32, in findAll
query = db.Data.find(upsert=True)
File "c:\users\cucumissativus\pycharmprojects\api\venv\lib\site-packages\werkzeug\local.py", line 316, in __get__
obj = instance._get_current_object() # type: ignore[misc]
File "c:\users\cucumissativus\pycharmprojects\api\venv\lib\site-packages\werkzeug\local.py", line 520, in _get_current_object
return get_name(local()) # type: ignore
File "C:\Users\CucumisSativus\PycharmProjects\api\application.py", line 17, in get_db
db = getattr(g, current_app.config['MONGO_DBNAME'])
File "c:\users\cucumissativus\pycharmprojects\api\venv\lib\site-packages\flask\ctx.py", line 52, in __getattr__
raise AttributeError(name) from None
AttributeError: Apitest1
Richard MacCutchan 16-Aug-22 4:18am    
Well one of the references to getattr is not valid. You need to use the debugger to see exactly what is happening when you try to get that information.
Prathmesh Upadhyay 16-Aug-22 4:29am    
I am not able to run pycharm dubugger while running flask on console
Prathmesh Upadhyay 16-Aug-22 5:17am    
i tried this:

def get_db():
"""
Configuration method to return db instance
"""
db = getattr(g, "_Apitest1", None)

if db is None:
db = g._database = PyMongo(current_app).db

return db


# Use LocalProxy to read the global db instance with just `db`
db = LocalProxy(get_db)

but it gave me :

File "C:\Users\CucumisSativus\PycharmProjects\api\application.py", line 32, in findAll
query = db.Data.find(upsert=True)Open an interactive python shell in this frame
AttributeError: 'NoneType' object has no attribute 'Data'
Richard MacCutchan 16-Aug-22 6:14am    
There is obviously something wrong with your code, and it is impossible to figure out what from here. If you cannot use the Python debugger then you need to add some print or logging statements to find out which of your references are not being set. Also take a look at the section on database access in the link I gave you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900