Search code examples
pythonflaskpython-importblueprint

Fix cicular import when importing Flask blueprint


I'm trying to import a Flask blueprint into my main file. However, when I do from flask_first.login_user.login import login, I get cannot import name 'login' from partially initialized module 'flask_first.login_user.login' (most likely due to a circular import) (C:\Users\Max\PycharmProjects\python1\flask_first\login_user\login.py). How do I fix this?

flask_first/login_user/login.py:

from flask_first.main import *
from flask import Blueprint
from flask_first.main import users, db
from flask_sqlalchemy import SQLAlchemy
from datetime import timedelta

@login.route('/')
def login():
    error = None
    if request.method == 'POST':  # checking if the method is POST, it means we got a query from button
        if request.form['nm'] == 'admin' or request.form['ps'] == 'secret':
            flash("You were successfully logged in into the admin's user page")
            session.permanent = True
            session['user'] = request.form['nm']
            password = request.form['ps']
            password = session['password']
            return redirect(url_for('administrating'))
        else:  # if we are not admins, continue with this code
            flash(f"You were successfully logged in", category='success')
            session.permanent = True  # setting the bool of session to permanent
            session['user'] = request.form[
                'nm']  # we are just saying that the session['user']= the name, which we typed into the field
            user1 = session['user']  # user1 not a function
            session['password'] = request.form['ps']  # session['password']= field, in which we typed our password
            password1 = request.form['ps']

            found_user = users.query.filter_by(name=user1,
                                               password=password1).first()  # we are filtering all the users in the database by the name and password, we typed while logging in
            if found_user:  # if we have found this user, we say that the email he typed previously is now in the field of email
                session[
                    'email'] = found_user.email  # we are saying that the email user typed previously, is now the session['email']
            else:
                usr = users(user1, '',
                            password1)  # if we haven't found that user by name and password, we create a new one
                db.session.add(usr)
                db.session.commit()
            return redirect(
                url_for('user'))  # redirecting to the user's page after logging in(using user's name)
    else:  # below is a standard script, which checks whether we are logged or not
        if 'user' in session:  # if user is already logged, it will download the user page.
            flash('You are already logged in, to log out, type logout')
            return redirect(url_for('user'))
        else:
            flash("You have not logged yet", category='success')
            return render_template('login_user.html', error=error)  # if it didn't go properly, we force the comeback
            # to the login_user page again

flask_first/main.py:

from datetime import timedelta
from flask import Flask, redirect, url_for, render_template, request, session, flash
from flask_sqlalchemy import SQLAlchemy
from flask_first.admin.second import second
from flask_first.login_user.login import login

app = Flask(__name__)
app.secret_key = 'hello world'
app.register_blueprint(second, url_prefix='/test')
app.register_blueprint(login, url_prefix='login_user')
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.sqlite3.html'  # access to the SQL
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.permanent_session_lifetime = timedelta(minutes=5)  # setting the time for long-lasting session
db = SQLAlchemy(app)

Solution

  • As the error suggests, you have a circular dependency issue. You are importing login from main and main from login. Modules cannot do that.

    Check out the "problems" section In this wiki https://en.m.wikipedia.org/wiki/Circular_dependency