AttributeError:模块'api.db'在Flask上没有属性'Model'

时间:2020-07-05 09:51:01

标签: python flask sqlalchemy flask-sqlalchemy

你好,我有以下文件夹结构

    .
    ├── api
    │   ├── users
    │   │   ├── __init__.py
    │   │   ├── model.py
    │   │   └── routes.py
│   ├── |__init__.py
    ├── __init__.py
    ├── requirements.txt
    └── server.py

api.__init__.py中,我有以下代码:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from api import users
from flask_restful import Api

db = SQLAlchemy()


def create_app(env):
    app = Flask(__name__)
    db.init_app(app)
    api = Api(app)
    users.register_routes(api)
    return app

,在users/model.py中,我有以下代码:

from sqlalchemy import Column, Integer, String
from .. import db

class User(db.Model):
    __tablename__ = 'users'
...

server.py中,我有以下代码:

import os

from api import create_app

app = create_app(os.getenv("ENV"))
if __name__ == "__main__":
    app.run(port=os.getenv("PORT"), debug=os.getenv("DEBUG")=='True')

问题是,当我执行server.py时,出现以下错误:

AttributeError:模块'api.db'没有属性'Model'

如何解决此错误?

谢谢

1 个答案:

答案 0 :(得分:1)

我建议您对项目的结构进行一些更改,以避免循环导入问题,并且建议您将应用程序作为软件包而不是作为模块导入,并且最好将__init __.py保留为{{1 }}和一些import,例如metadata__author__

__version__

api .. errors (blueprint) .. __init__.py .. routes.py .. users (blueprint) .. __init__.py .. model.py .. routes.py .. extensions.py .. __init__.py .. app.py (here where your define "create_app()" function) server.py requirements.txt 中:

api/users/__init __.py

from .routes import bp 中:

api/users/models.py

from api.extensions import db # from sqlalchemy import Column, Integer, String # You don't need this since you already imported the db oject class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) # here ... 中:

api/users/routes.py

from flask import Blueprint, request, jsonify .. from api.extensions import db # maybe you need it here from .models import User # Your model bp = Blueprint('users', __name__) # instantiate your 'users' Blueprint @bp.route('/', methods=['GET', 'POST']) def index(): .. return jsonify(..) 中,定义您的应用所需的/api/extensions.py扩展名

Flask

from flask_sqlalchemy import SQLAlchemy .. db = SQLAlchemy() .. 中:

/api/__init __.py

from .app import create_app 中:

/api/app.py

from flask import Flask .. def create_app(config_object): """Create a Flask application using the app factory pattern.""" app = Flask(__name__) """Load configuration.""" # app.config.from_object(CONFIGS[config_object]) # an example .. """Init app extensions.""" from .extensions import db db.init_app(app) .. """Register blueprints.""" from .errors import bp as errors_bp app.register_blueprint(errors_bp) from .users import bp as users_bp app.register_blueprint(users_bp, url_prefix='/users') .. return app 中:

/server.py