你好,我有以下文件夹结构
.
├── 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'
如何解决此错误?
谢谢
答案 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