Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing python objects from main flask app to blueprints

Tags:

python

flask

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??

like image 915
d0ppL3G Avatar asked Aug 16 '26 16:08

d0ppL3G


1 Answers

The idea you are attempting is correct; however it just needs to be done a little differently.

First, start by declaring your mongo object in your application factory:

In your app/__init__.py:

import pymongo
from flask import Flask
    
mongo = pymongo.MongoClient(
                        host='mongodb+srv://<username>:<passwrd>@cluster0.bslkwxdx.mongodb.net/?retryWrites=true&w=majority',
                        serverSelectionTimeoutMS = 1000
                    )
# Mongo is declared outside of function

def create_app(app):
    app = Flask(__name__)
    return app

And then in your other blueprint, you would call:

from app import mongo # This right here will get you the mongo object
from flask import Blueprint
    
bp_1 = Blueprint('bp1', __name__, static_folder='static', template_folder='templates')
db = mongo
like image 189
Countzen Avatar answered Aug 18 '26 07:08

Countzen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!