Flask SQLAlchemy import DB import

南笙酒味 提交于 2020-01-24 21:19:09

问题


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:


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)


来源:https://stackoverflow.com/questions/56048656/flask-sqlalchemy-import-db-import

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!