При запуске приложения вылазит ошибка: cannot import name 'db' from partially initialized module 'sweater' (most likely due to a circular import).
Нашел способ как её убрать, импортировав from sweater import db, from sweater.models import User внутрь функций в модуле routes.py. Не знаю, правильно ли это, подскажите пожалуйста.
Вот код:
__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)
И вот работающий код 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
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)