0

I have three files: params.py like this:

from flask_pymongo import PyMongo
mongo = PyMongo()

server.py like this:

from params import mongo
mongo.init_app(app)

A function regarding a post in a blueprint in views.py like this:

from params import mongo
...
mongo.db.courses_cache.find_one_and_update({'uid': 100}, {'$set': {'data': {}, 'hash': '123'}}, upsert=True)

And it has error like this:

mongo.db.courses_cache.find_one_and_update({'uid': 100}, {'$set': {'data': {}, 'hash': '123'}}, upsert=True) AttributeError: 'NoneType' object has no attribute 'courses_cache'

But if I write this mongo op right after "mongo.init_app(app)", it is okay.

mongo.db just becomes "None" in other python files.

I have been using flask-sqlalchemy like this way with zero error, why can't flask-pymongo?

1 Answers1

0

You cannot use the PyMongo instance until after init_app is called -- my guess is that in your views.py, you haven't yet imported server.py or otherwise made sure that init_app is called.

dcrosta
  • 26,009
  • 8
  • 71
  • 83
  • The easiest way to fix these errors is to move your collection code to be inside one of your routes. This way you're guaranteed to only access the collection after initialization – Aditya Garg Sep 01 '20 at 23:28