Flask SQLAlchemy导入DB导入

时间:2019-05-08 20:34:35

标签: python python-3.x flask flask-sqlalchemy

我在将烧瓶与SQLAlchemy一起使用,设置所有配置设置后,在模型上出现数据库导入错误。

导入错误:无法导入名称“ db”

我的主应用程序 __ 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)

我的控制器和模型位于app / test / test.py和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'}

我的 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 个答案:

答案 0 :(得分:0)

您正在使用Flask工厂方法,因此请在模型中初始化SqlAlchemy并将其导入到__init__.py文件

因此model.py变为

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)

然后在__init__.py中变成

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)