烧瓶sqlalchemy导入DB导入



我正在使用sqlalchemy的烧瓶,设置了所有配置设置后,我在模型上获得了DB导入错误。

Importerror:无法导入名称'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)

在应用程序/test/test.py和model.py.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)

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

so 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)

相关内容

  • 没有找到相关文章

最新更新