Flask-Pymongo DB is returning as None

461 views Asked by At

I am trying create a webapp with Flask-Pymongo, but it is saying that my database does not exist.

This is my __init__.py:

import os
from flask import Flask
from flask_pymongo import PyMongo

mongo = PyMongo()

def init_app():

    app = Flask(__name__)
    app.config.from_pyfile('config.py')
    mongo.init_app(app)
    
    with app.app_context():
        from temp.routes.stage_routes import stage_route
        app.register_blueprint(stage_route)
    
    return app

This is my db.py (temp is the top level directory)

from temp.__init__ import mongo

db = mongo.db

and this is one of my blueprints with routes to query the database

from flask import Blueprint

from temp.db import db

stage_route = Blueprint('stage_route', __name__, url_prefix='/stages')

@stage_route.route('/')
def home():
    return 'This is the home page for the stage blueprint'

@stage_route.route('/all')
def all():
    stage = db.stages.find() # This is where the error is
    print(stage)

For some reason I get the error saying that "NoneType does not have attribute 'stages'" because it is saying that the db variable is none. I can't figure out why this is is happening since the database and the collection does exist and the MONGO_URI string is loaded from the config file. I can see that it is connecting on the mongodb side, but i'm assuming it has something to do with my create_app() function in the init.py file. Do you see something that I am missing? Any help would be appreciated

3

There are 3 answers

0
ProjectRexa On

The code is missing the connection URI string, as mentioned in the documentation -

from flask import Flask
from flask_pymongo import PyMongo

app = Flask(__name__)

# The missing URI
app.config["MONGO_URI"] = "mongodb://localhost:27017/myDatabase"

mongo = PyMongo(app)
0
Dhia Eddine Benterki On

I think the probleme is that you are connecting to the cluster , and the cluster has many databases , so you need to specify which database you are connecting to. I have encountered the same probleme and this is how I fixed it The first way to Fix it is to specift the name of the database after the cluster name like so.

MONGO_URI="mongodb+srv://<username>:<password>@<cluster-name>/<databasename>?retryWrites=true&w=majority"

Using this first way you can acess the "db" attribute of the mongo object directly. like the example below

from flask import Blueprint
from .extensions import mongo
from pymongo.database import Database

main: Blueprint = Blueprint("main", __name__)


@main.route("/")
def home():
    
    mongo.db.books.insert_one({"name": "Meditations by Me"})

    return "book inserted !"

The second way is to acess the database the classic pymongo way without needing to add the database name in the uri using the MongoClient which is the same as the cx attribute under the mongo object like so, In my example the name of my database is library

from flask import Blueprint
from .extensions import mongo
from pymongo.database import Database

main: Blueprint = Blueprint("main", __name__)


@main.route("/")
def home():
    
    mongo.cx.library.books.insert_one({"name": "Meditations by Me"})

    return "book inserted !"

databases like library can be acessed directly just like an attribute in the MongoClient object , the same as collections under Databases.

I used the Flask-pymongo and PyMongo documentations pages as refrences : https://pymongo.readthedocs.io/en/stable/tutorial.html https://flask-pymongo.readthedocs.io/en/latest/#flask_pymongo.PyMongo

1
Mehul Batra On

mongo = PyMongo(app).cx["your_database_name"]