Passing python objects from main flask app to blueprints

Viewed 23

I am trying to define a mongodb object inside main flask app. And I want to send that object to one of the blueprints that I created. I may have to create more database objects in main app and import them in different blueprints. I tried to do it this way.

from flask import Flask, render_template
import pymongo
from admin_component.bp1 import bp_1

def init_db1():
    try:
        mongo = pymongo.MongoClient(
            host='mongodb+srv://<username>:<passwrd>@cluster0.bslkwxdx.mongodb.net/?retryWrites=true&w=majority',
            serverSelectionTimeoutMS = 1000
        )
        db1 = mongo.test_db1.test_collection1
        mongo.server_info()  #this is the line that triggers exception.
        return db1
    except:
        print('Cannot connect to db!!')


app = Flask(__name__)
app.register_blueprint(bp_1, url_prefix='/admin')  #only if we see /admin in url we gonna extend things in bp_1


with app.app_context():
    db1 = init_db1()

@app.route('/')
def test():
    return '<h1>This is a Test</h1>'

if __name__ == '__main__':
    app.run(port=10001, debug=True)

And this is the blueprint and I tried to import the init_db1 using current_app.

from flask import Blueprint, render_template, Response, request, current_app
import pymongo
from bson.objectid import ObjectId
import json

bp_1 = Blueprint('bp1', __name__, static_folder='static', template_folder='templates')
print(current_app.config)
db = current_app.config['db1']

But it gives this error without specifying more details into deep.

  raise RuntimeError(unbound_message) from None
RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
the current application. To solve this, set up an application context
with app.app_context(). See the documentation for more information.

Can someone point out what am I doing wrong here??

0 Answers
Related