python import conflict with flask-security

一笑奈何 提交于 2019-12-23 05:29:16

问题


I run into this "import conflict" fairly often I'm trying to find the most Python way to solve it. My app's __init__ instantiates db and over in my user.models file, db is referenced extensively. However, to use Flask-Security, I need to initialize the user_datastore which requires both my db and my User model. These files can't import each other. I need User in the __init__ method but I also need the db over in the User model.

I've tried all sorts of arrangements (short of moving my many interconnected models into the __init__ file), but here's the simplest setup and traceback. Also followed Python import conflict but haven't quite gotten my head around it.

__init__.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flaskext.markdown import Markdown
from flask_uploads import UploadSet, configure_uploads, IMAGES
from flask_security import Security, SQLAlchemyUserDatastore, utils
from flask_mail import Mail
import private

app = Flask(__name__)
app.config.from_object('settings')
db = SQLAlchemy(app)
mail = Mail(app)

# migrations
migrate = Migrate(app, db)

# markdown
md = Markdown(app, extensions=['fenced_code', 'tables'])

# images
uploaded_images = UploadSet('images', IMAGES)
configure_uploads(app, uploaded_images)

# CONFLICT 
from user.models import User, Role    
# Setup Flask-Security
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)


from roster import views
from sentence import views
from blog import views
from user import views

@app.before_first_request
def before_first_request():

    # Create the Roles "admin" and "end-user" -- unless they already exist
    user_datastore.find_or_create_role(name='admin', description='Administrator')
    user_datastore.find_or_create_role(name='end-user', description='End user')

    # Create two Users for testing purposes -- unless they already exists.
    # In each case, use Flask-Security utility function to encrypt the password.
    encrypted_password = utils.encrypt_password(private.STARTING_ADMIN_PASS)
    if not user_datastore.get_user('example@gmail.com'):
        user_datastore.create_user(email='example@gmail.com', password=encrypted_password)

    db.session.commit()

    user_datastore.add_role_to_user('example@gmail.com', 'admin')
    db.session.commit()

user.models

# THE OTHER HALF OF THE CONFLICT
from my_app import db
from blog.models import Post
from sentence.models import Sentence
from roster.models import Roster
from datetime import datetime
import datetime
from flask_security import UserMixin, RoleMixin

# Helper table for a many-to-many relationship
roles_users = db.Table('roles_users',
        db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
        db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))

class Role(db.Model, RoleMixin):
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(80), unique=True)
    description = db.Column(db.String(255))

class User(db.Model, UserMixin):
    # general variables
    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(155))
    last_name = db.Column(db.String(155))
    email = db.Column(db.String(255), unique=True)
    password = db.Column(db.String(255))
    active = db.Column(db.Boolean())
    confirmed_at = db.Column(db.DateTime())

    # relations
    roles = db.relationship('Role', secondary=roles_users,
                            backref=db.backref('users', lazy='dynamic'))
    posts = db.relationship('Post', backref='user', lazy='dynamic')
    sentences = db.relationship('Sentence', backref='user', lazy='dynamic')

    def __init__(self, name, email):
        # create a roster
        roster = Roster("default", self.email)
        db.session.add(roster)
        db.session.commit()

    def __repr__(self):
        return '<User %r>' % self.username

    # __str__ is required by Flask-Admin (not using?), so we can have human-readable values for the Role when editing a User.
    # If we were using Python 2.7, this would be __unicode__ instead.
    def __str__(self):
        return self.name

    # __hash__ is required to avoid the exception TypeError: unhashable type: 'Role' when saving a User
    def __hash__(self):
        return hash(self.name)

Traceback

Traceback (most recent call last):
  File "manage.py", line 8, in <module>
    from my_app import app
  File "/home/ubuntu/workspace/my_app/__init__.py", line 9, in <module>
    from user.models import User, Role
  File "/home/ubuntu/workspace/my_app/user/models.py", line 1, in <module>
    from my_app import db
ImportError: cannot import name 'db'

回答1:


What I usually do is create an extension.py with the used extensions and use an app factory to initialize them

extensions.py

from flask_security import Security
from flask_sqlalchemy import SQLAlchemy

security = Security()
db = SQLAlchemy()

Then in the __init__.py I do the initialization

def register_extensions(app):
    db.init_app(app)
    security.init_app(app, ...)

So you can import db, security and other extensions in other classes and you have no import errors. For more information and explanation check the Flask documentation about Application Factories



来源:https://stackoverflow.com/questions/43812329/python-import-conflict-with-flask-security

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!