OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

How import flask SQLAlchemy db to blueprints?

  • Thread starter Thread starter Dan Butk
  • Start date Start date
D

Dan Butk

Guest
I have a Flaks application with modules. What approach should I use to create instances of SQLAlchemy in the blueprints? My init.py

Code:
from flask import Flask
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from .config import PGHOST, PGUSER, PGPORT, PGDATABASE, PGPASSWORD
from .auth import auth_bp
from .user_ui import user_ui_bp



def create_app():
    app = Flask(__name__)
    CORS(app)
    app.config['SQLALCHEMY_DATABASE_URI'] = f"postgresql://{PGUSER}:{PGPASSWORD}@{PGHOST}:{PGPORT}/{PGDATABASE}"
    app.config['SECRET_KEY'] = "secret_key"
    db = SQLAlchemy(app)
    db.init_app(app)
    

    # Register Blueprints
    app.register_blueprint(auth_bp)
    app.register_blueprint(user_ui_bp)

    return app

Code:
my auth.py blueprint
import datetime
import jwt
import bcrypt
from flask import Blueprint, request, jsonify
from .db_utils import DbUser
from .config import SECRET_KEY

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/api/register', methods=["POST"])
def register():
    data = request.get_json()
    password = data['password'].encode('utf-8')

    # Hash the password
    hashed_password = bcrypt.hashpw(password, bcrypt.gensalt())

    user = DbUser(username=data['username'], password=hashed_password.decode('utf-8'))
    db.session.add(user)
    db.session.commit()
    return jsonify({'message': 'User registered successfully'}), 201


I need initiate db, but I have no idea where I should import it from. 
I am not even sure what approach I should be using.

I tried initiating new instance of SQLAlchemy in my blueprint

db = SQLAlchemy()

But then it ended up with "RuntimeError: A 'SQLAlchemy' instance has already been registered on this Flask app. Import and use that instance instead." I also tried importing db from app, but "ImportError: cannot import name 'db' from partially initialized module 'app' (most likely due to a circular import)" Also tried

db = current_app.config['db'] But get error

Code:
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.

I feel like getting context from current app makes the most sense but I am not sure how to approach this...
<p>I have a Flaks application with modules. What approach should I use to create instances of SQLAlchemy in the blueprints? My init.py</p>
<pre><code>from flask import Flask
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from .config import PGHOST, PGUSER, PGPORT, PGDATABASE, PGPASSWORD
from .auth import auth_bp
from .user_ui import user_ui_bp



def create_app():
app = Flask(__name__)
CORS(app)
app.config['SQLALCHEMY_DATABASE_URI'] = f"postgresql://{PGUSER}:{PGPASSWORD}@{PGHOST}:{PGPORT}/{PGDATABASE}"
app.config['SECRET_KEY'] = "secret_key"
db = SQLAlchemy(app)
db.init_app(app)


# Register Blueprints
app.register_blueprint(auth_bp)
app.register_blueprint(user_ui_bp)

return app
</code></pre>
<pre><code>
my auth.py blueprint
import datetime
import jwt
import bcrypt
from flask import Blueprint, request, jsonify
from .db_utils import DbUser
from .config import SECRET_KEY

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/api/register', methods=["POST"])
def register():
data = request.get_json()
password = data['password'].encode('utf-8')

# Hash the password
hashed_password = bcrypt.hashpw(password, bcrypt.gensalt())

user = DbUser(username=data['username'], password=hashed_password.decode('utf-8'))
db.session.add(user)
db.session.commit()
return jsonify({'message': 'User registered successfully'}), 201


I need initiate db, but I have no idea where I should import it from.
I am not even sure what approach I should be using.
</code></pre>
<p>I tried initiating new instance of SQLAlchemy in my blueprint</p>
<p><code>db = SQLAlchemy()</code></p>
<p>But then it ended up with "RuntimeError: A 'SQLAlchemy' instance has already been registered on this Flask app. Import and use that instance instead."
I also tried importing db from app, but "ImportError: cannot import name 'db' from partially initialized module 'app' (most likely due to a circular import)"
Also tried</p>
<p><code>db = current_app.config['db']</code>
But get error</p>
<pre><code>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.
</code></pre>
<p>I feel like getting context from current app makes the most sense but I am not sure how to approach this...</p>
 
Top