3

I am using flask with SQLAlchemy, after set all configuration setting I got db import error on model.

ImportError: cannot import name 'db'

my main app __init__

from flask_api import FlaskAPI
from flask_sqlalchemy import SQLAlchemy
import os
import json
from flask import Flask
from flask_pymongo import PyMongo
from flask import request

from app.test.controllers import test


def create_app(config_name):
    app = FlaskAPI(__name__)
    CORS(app)
    app.config.from_object(os.environ['APP_SETTINGS'])
    db = SQLAlchemy(app)
    from app.test.controllers import test
    app.register_blueprint(test)

my controller and model in app/test/test.py and model.py

test.py

from flask import Blueprint, request, redirect, url_for
import json
from flask_sqlalchemy import SQLAlchemy

from app.test.model import TestModel

test = Blueprint('test', __name__, url_prefix='/api/v1')


@test.route('/test/store', methods=['POST'])
def store():
    return json.dumps({'success':True}), 200, {'ContentType':'application/json'}

my model.py

from app import db

class TestModel(db.Model):
    __tablename__ = 'user_profiles'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255), unique=False)
    email= db.Column(db.String(255), unique=False)


    def __init__(self, name=None, email=None):
        self.name = name
        self.email = email

    def __repr__(self):
        return '<User %r>' % (self.name, self.email)

1 Answer 1

3

You are using the Flask factory method so initialize SqlAlchemy in your model and import it to your __init__.py file

So model.py becomes

from flask_sqlalchemy import SQLAlchemy    
db = SQLAlchemy()

class TestModel(db.Model):
    __tablename__ = 'user_profiles'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255), unique=False)
    email= db.Column(db.String(255), unique=False)


    def __init__(self, name=None, email=None):
        self.name = name
        self.email = email

    def __repr__(self):
        return '<User %r>' % (self.name, self.email)

Then in __init__.py it becomes

from flask_api import FlaskAPI
from model import db
import os
import json
from flask import Flask
from flask_pymongo import PyMongo
from flask import request

from app.test.controllers import test


def create_app(config_name):
    app = FlaskAPI(__name__)
    CORS(app)
    app.config.from_object(os.environ['APP_SETTINGS'])
    db.init_app(app)
    from app.test.controllers import test
    app.register_blueprint(test)
Sign up to request clarification or add additional context in comments.

3 Comments

hi, so if there is multiple models. how can i import db
i want single init file which creates the db instance and then any model can access it.
If you want multiple model files, then you can put them a package(lets call the package models) and in the init.py file of the models package, you create the db object and import it where ever its needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.