[Python] Bug related with circular imports using Flask

Discussão em 'Python' iniciado por Stack, Abril 12, 2025.

  1. Stack

    Stack Membro Participativo

    So i have some flask code, two files affected one is flask_app.py and the other one is routes.py. The error thrown were ranging from

    Error running WSGI application
    2025-03-16 23:05:30,980: ImportError: cannot import name 'app' from partially initialized module 'flask_app' (most likely due to a circular import) (/home/Winternet/mysite/flask_app.py)
    2025-03-16 23:05:30,980: File "/var/www/winternet_pythonanywhere_com_wsgi.py", line 16, in <module>
    2025-03-16 23:05:30,981: File "/home/Winternet/mysite/flask_app.py", line 7, in <module>
    2025-03-16 23:05:30,981: import routes
    2025-03-16 23:05:30,981:
    2025-03-16 23:05:30,981: File "/home/Winternet/mysite/routes.py", line 4, in <module>
    2025-03-16 23:05:30,981: from flask_app import app, dbx
    2025-03-16 23:05:30,981: ***************************************************
    2025-03-16 23:05:30,982: If you're seeing an import error and don't know why,
    2025-03-16 23:05:30,982: we have a dedicated help page to help you debug:
    2025-03-16 23:05:30,982: https://help.pythonanywhere.com/pages/DebuggingImportError/
    2025-03-16 23:05:30,982: ***************************************************


    to

    rror running WSGI application
    2025-03-11 01:34:01,760: ImportError: cannot import name 'restricted_users' from partially initialized module 'flask_app' (most likely due to a circular import) (/home/Winternet/mysite/flask_app.py)
    2025-03-11 01:34:01,760: File "/var/www/winternet_pythonanywhere_com_wsgi.py", line 16, in <module>
    2025-03-11 01:34:01,761: from flask_app import app as application # noqa
    2025-03-11 01:34:01,761:
    2025-03-11 01:34:01,761: File "/home/Winternet/mysite/flask_app.py", line 69, in <module>
    2025-03-11 01:34:01,761: import routes
    2025-03-11 01:34:01,761:
    2025-03-11 01:34:01,762: File "/home/Winternet/mysite/routes.py", line 4, in <module>
    2025-03-11 01:34:01,762: from flask_app import app, dbx, restricted_users,sudo_users, locked_users, RECAPTCHA_SECRET_KEY, RECAPTCHA_SITE_KEY
    2025-03-11 01:34:01,762: ***************************************************
    2025-03-11 01:34:01,762: If you're seeing an import error and don't know why,
    2025-03-11 01:34:01,762: we have a dedicated help page to help you debug:
    2025-03-11 01:34:01,763: https://help.pythonanywhere.com/pages/DebuggingImportError/
    2025-03-11 01:34:01,763: ***************************************************


    for debugging purposes, here is the content of flask_app.py:

    from flask import Flask
    import dropbox
    import os
    from dotenv import load_dotenv # Import dotenv
    from authlib.integrations.flask_client import OAuth
    from config import Config
    import routes


    app = Flask(__name__)
    app.debug = (flask_env == 'development')
    app.secret_key = 'super secret key'
    DROPBOX_ACCESS_TOKEN = Config.DROPBOX_ACCESS_TOKEN
    key = Config.DROPBOX_KEY
    secret = Config.DROPBOX_SECRET
    refresh = Config.DROPBOX_REFRESH

    # Initialize Dropbox client
    dbx = dropbox.Dropbox(
    app_key=key,
    app_secret=secret,
    oauth2_refresh_token=refresh
    )
    # Load environment variables from .flaskenv
    load_dotenv()
    import routes

    # Detect the Flask environment mode
    flask_env = 'development' if os.path.exists('debug.txt') else 'production'
    print(f"Running in {flask_env} mode") # Debug message

    # TODO Add rendering of the media variably so until not scrolled its not rendered for bandwidht reduction
    if flask_env == 'development':
    RECAPTCHA_SITE_KEY = '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI'
    RECAPTCHA_SECRET_KEY ='6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe'
    else:
    RECAPTCHA_SITE_KEY = '6LeoUaEpAAAAAJM8e3CtUlWhmYb0GwrTMsoZsoTK'
    RECAPTCHA_SECRET_KEY ='6LeoUaEpAAAAADM7HXZk9qI8CyzH8jSkJPlNnqv-'
    print(f"Recaptcha Site Key: {RECAPTCHA_SITE_KEY}") # Debug message

    app = Flask(__name__)
    app.debug = (flask_env == 'development')
    app.secret_key = 'super secret key'

    last_post_time = {}

    # Set up & Initialize OAuth
    oauth = OAuth(app)
    oauth.register(
    name='google',
    client_id=os.getenv('GOOGLE_CLIENT_ID'),
    client_secret=os.getenv('GOOGLE_CLIENT_SECRET'),
    authorize_url='https://accounts.google.com/o/oauth2/auth',
    access_token_url='https://accounts.google.com/o/oauth2/token',
    redirect_uri='http://localhost:8000/auth/callback',
    client_kwargs={'scope': 'openid profile email'}
    )

    # Ici, pour les groupes et autres données, vous pourrez également migrer vers MySQL.
    # Pour cet exemple, nous initialisons des listes vides.
    groups = []
    group_posts = []
    locked_users = set()
    app.config.from_object(Config)

    # Set up Dropbox access token
    DROPBOX_ACCESS_TOKEN = Config.DROPBOX_ACCESS_TOKEN
    key = Config.DROPBOX_KEY
    secret = Config.DROPBOX_SECRET
    refresh = Config.DROPBOX_REFRESH

    # Initialize Dropbox client
    dbx = dropbox.Dropbox(
    app_key=key,
    app_secret=secret,
    oauth2_refresh_token=refresh
    )
    if flask_env == 'development':
    app.debug = True
    else:
    app.debug = False

    from time import sleep


    if __name__ == '__main__':
    app.run(host='0.0.0.0',debug=False, port=8000)


    and here is a snippet of the affected part of routes.py

    from flask import render_template, request, session, redirect, url_for, jsonify, flash, Response
    from werkzeug.utils import secure_filename
    from functionsdb import DataClass, get_db_connection, read_posts, read_users
    from flask_app import app, dbx
    from markupsafe import Markup, escape # Ne pas enlever
    import requests
    import threading
    import csv
    from flask_app import restricted_users,sudo_users, locked_users, RECAPTCHA_SECRET_KEY, RECAPTCHA_SITE_KEY

    # Constants for timing (in seconds)
    POST_LIMIT = 30
    EXTENDED_LIMIT = 5 * 60
    min_char = 30
    last_post_time = {} # Dictionary to store timestamps per user
    failed_attempts = {}


    PROFILE_FILE = 'profile.csv'
    CSV_FILE = 'servers.csv'


    So i tried moving around imports from place to place, but the behavior was just changing to different types of (сircular import) errors. I expected it to solve the problem, like multiple AI's told me, but it didnt.

    Continue reading...

Compartilhe esta Página