B
B
Balundula2022-04-13 16:39:51
Flask
Balundula, 2022-04-13 16:39:51

How to fix cannot import name 'db' from partially initialized module 'sweater' (most likely due to a circular import) error?

When starting the application, an error pops up: cannot import name 'db' from partially initialized module 'sweater' (most likely due to a circular import).
I found a way to remove it by importing from sweater import db, from sweater.models import User inside functions in the routes.py module. I don't know if this is correct, please tell me.

Here is the code:
__init__.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

from flask_login import LoginManager

from sweater.routes import app_route

app = Flask(__name__)
app.register_blueprint(app_route)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy()
login_manager = LoginManager()


routes.py
from flask import render_template, request, flash, redirect, Blueprint
from werkzeug.security import generate_password_hash, check_password_hash

from flask_login import login_user

from sweater import db
from sweater.models import User


app_route = Blueprint('app_route', __name__)


@app_route.route('/')
def index():
    return render_template('base.html')


@app_route.route('/register', methods=['POST', 'GET'])
def register():
    login = request.form.get('login')
    password = request.form.get('pass')
    password2 = request.form.get('pass2')

    if request.method == 'POST':
        if not (login or password or password2):
            flash('Пожалуйста заполните поля')
        elif password != password2:
            flash('Пароли не совпадают')
        else:
            new_user = User(login=login, password=generate_password_hash(password))
            try:
                db.session.add(new_user)
                db.session.commit()
                return redirect('/login')
            except:
                flash('При регистрации произошла ошибка')
    else:
        return render_template('register.html')


@app_route.route('/login', methods=['POST', 'GET'])
def login_page():
    login = request.form.get('login')
    password = request.form.get('pass')

    if login and password:
        user = User.query.filter_by(login=login).first()
        if check_password_hash(user.passwoord, password):
            login_user(user)
            return 'Вы вошли'
        else:
            flash('Вы ввели не верные данные')
    else:
        return render_template('login.html')


@app_route.route('/logout')
def logout():
    pass


@app_route.route('/profile/<int:user_id>')
def profile(user_id):
    return render_template ('profile.html',  user_id=user_id)


@app_route.route('/db')
def db_page():
    users = User.query.order_by(User.date).all()
    return render_template('db.html', users=users)


@app_route.route('/test')
def test():
    test = User.query.filter_by(login='Glipher').first()
    return render_template('test.html', test=test)


models.py
from sweater import db, login_manager


from flask_login import UserMixin

from datetime import datetime


class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    login = db.Column(db.String(128), nullable=False, unique=True)
    password = db.Column(db.String(128), nullable=False)
    date = db.Column(db.DateTime, default=datetime.utcnow)


@login_manager.user_loader
def load_user(user_id):
    return User.query.ger(user_id)


And here is the working routes.py code:
from flask import render_template, request, flash, redirect, Blueprint
from werkzeug.security import generate_password_hash, check_password_hash

from flask_login import login_user

app_route = Blueprint('app_route', __name__)


@app_route.route('/')
def index():
    return render_template('base.html')


@app_route.route('/register', methods=['POST', 'GET'])
def register():
    from sweater import db
    from sweater.models import User

    login = request.form.get('login')
    password = request.form.get('pass')
    password2 = request.form.get('pass2')

    if request.method == 'POST':
        if not (login or password or password2):
            flash('Пожалуйста заполните поля')
        elif password != password2:
            flash('Пароли не совпадают')
        else:
            new_user = User(login=login, password=generate_password_hash(password))
            try:
                db.session.add(new_user)
                db.session.commit()
                return redirect('/login')
            except:
                flash('При регистрации произошла ошибка')
    else:
        return render_template('register.html')


@app_route.route('/login', methods=['POST', 'GET'])
def login_page():
    from sweater.models import User

    login = request.form.get('login')
    password = request.form.get('pass')

    if login and password:
        user = User.query.filter_by(login=login).first()
        if check_password_hash(user.passwoord, password):
            login_user(user)
            return 'Вы вошли'
        else:
            flash('Вы ввели не верные данные')
    else:
        return render_template('login.html')


@app_route.route('/logout')
def logout():
    pass


@app_route.route('/profile/<int:user_id>')
def profile(user_id):
    return render_template ('profile.html',  user_id=user_id)


@app_route.route('/db')
def db_page():
    from sweater.models import User

    users = User.query.order_by(User.date).all()
    return render_template('db.html', users=users)


@app_route.route('/test')
def test():
    from sweater.models import User
    
    test = User.query.filter_by(login='Glipher').first()
    return render_template('test.html', test=test)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question