0

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

Gerardo Zinno
  • 1,518
  • 1
  • 13
  • 35
Derithus
  • 21
  • 2
  • Where is your connection string? or attempt to connect to mongodb. I am guessing you are using this wrapper? [flask_pymongo](https://flask-pymongo.readthedocs.io/en/latest/#:~:text=Flask-PyMongo%20wraps%20PyMongo%E2%80%99s%20MongoClient%20%2C%20Database%2C%20and%20Collection,allowing%20user%20code%20to%20use%20MongoDB-style%20dotted%20expressions.) – Koodies Jan 25 '23 at 02:13

1 Answers1

0

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)