问题
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