如何在使用Flask SQLAlchemy模型的Flask应用程序中避免循环导入? [英] How to avoid circular imports in a Flask app with Flask SQLAlchemy models?

查看:87
本文介绍了如何在使用Flask SQLAlchemy模型的Flask应用程序中避免循环导入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要进入Flask并构建一个使用Flask SQLAlchemy的应用程序.我创建了一个基本的API,当所有代码都在一个文件中时,该API可以工作,但是希望更好地组织它,如下所示:

I'm getting into Flask and building out an app that uses Flask SQLAlchemy. I've created a basic API that works when all the code is in a single file, but would like to better organize it, like so:

app/models/user.py

from datetime import datetime
from app.app import db


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    public_id = db.Column(db.String, unique=True)
    admin = db.Column(db.Boolean)
    username = db.Column(db.String(50), unique=True)
    email = db.Column(db.String(50), unique=True)
    password = db.Column(db.String(100))
    subscription_plan = db.Column(db.Integer)
    created_at = db.Column(db.DateTime, index=True,
                           default=datetime.utcnow())
    updated_at = db.Column(db.DateTime, index=True, default=datetime.utcnow())

app/app.py

from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash
import uuid

from app.models.user import User

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = #SQLALCHEMY_DATABASE_URI

db = SQLAlchemy(app)

# ... CRUD routes that will use User

@app.route('/user', methods=['POST'])
def create_user():
data = request.get_json()
hashed_password = generate_password_hash(data['password'])
new_user = User(
    public_id=str(uuid.uuid4()),
    username=data['username'],
    password=hashed_password,
    email=data['email'],
    admin=data['admin'],
    subscription_plan=data['subscription_plan']
)
db.session.add(new_user)
db.session.commit()
return jsonify({'message': 'User successfully created.'})


if __name__ == '__main__':
    app.run(port=5000, debug=True)

我想从 app/app.py 导入 db 到我的 app/models/user.py 文件中,但是当我然后尝试将 User 模型导入到 app/app.py 中,由于循环导入,这给了我一个错误.我不知道该如何解决,因为 User app传递 app 实例后,似乎需要 db /app.py .

I would like to import db from app/app.py into my app/models/user.py file, but when I then try to import the User model into app/app.py, it gives me an error because of the circular import. I have no idea how to get around this because it seems like User needs db after it gets passed an instance of app from app/app.py.

我也想将路线从此处移出并移至单独的文件中,以便更好地进行组织,因此请尝试了解避免在周围进行循环进口的最佳方法.任何帮助都将不胜感激!

I'd also like to move my routes out of here and into separate files for better organization, so trying to understand the best way to avoid circular imports all around. Any and all help is greatly appreciated!

推荐答案

而不是让用户导入应用程序和应用程序导入用户,而是通过 init 将它们组合在一起.

Instead of having User import app and app import user, bring them together in init.

app/app.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
db = SQLAlchemy(app)

app/models/user.py

from app.app import db
class User:
    pass #access db the way you want

app/views.py

from app.app import app,db
@app.route("/")
def home():
    return "Hello World" # use db as you want

app/__ init __.py

from app import app
from app.models.user import User
from app import views

这是解决该问题的最简单方法.但是,我建议使用应用工厂

This is the leanest fix to the problem. However, I would recommend using Application Factories

这篇关于如何在使用Flask SQLAlchemy模型的Flask应用程序中避免循环导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆