netlemon
netlemon

Reputation: 1053

Flask circular import using Blueprints

I am trying to get the app instance in a "blueprint" directory, but keep getting circular import error.

The file tree of root directory app

├── __init__.py
├── app.db
├── config.py
├── main
│   ├── __init__.py
│   └── routes.py
├── models.py
├── projects
│   ├── __init__.py
│   ├── forms.py
│   └── routes.py
└── users
    ├── __init__.py
    ├── forms.py
    └── routes.py

I want the app to be imported and used in the projects/routes.py file:

app/projects/routes.py

import os
from flask import render_template, url_for, flash, redirect, Blueprint, request

from run import app # <- this is the line that triggers the error

# some other code

portfolio = Blueprint('portfolio', __name__)

app/init.py

def create_app(config_class=Config):

  app = Flask(__name__)

  # some other code

  from app.projects.routes import portfolio
  app.register_blueprint(portfolio)

  # some other code
  
  return app

run.py is above one level than the root directory aftermentioned.

run.py

from app import create_app

app = create_app()

if __name__ == '__main__':
    app.run()

from app.models import User
from app import db

Traceback of the error

flask.cli.NoAppException: While importing "run", an ImportError was raised:  Traceback (most recent call last): File "/Users/berry/Environments/Progresso Nel Edilzia/progresso/lib/python3.8/site-packages/flask/cli.py", line 240, in locate_app __import__(module_name) File "/Users/berry/Environments/Progresso Nel Edilzia/run.py", line 3, in <module> app = create_app() File "/Users/berry/Environments/Progresso Nel Edilzia/app/__init__.py", line 39, in create_app from app.projects.routes import portfolio File "/Users/berry/Environments/Progresso Nel Edilzia/app/projects/routes.py", line 10, in <module> from run import app ImportError: cannot import name 'app' from partially initialized module 'run' (most likely due to a circular import) (/Users/berry/Environments/Progresso Nel Edilzia/run.py)

Upvotes: 4

Views: 1364

Answers (1)

joshua
joshua

Reputation: 335

If you need app object ,you can from flask import current_app

if you need use app outside requests-context,you can import app in fucntion

def foo_func():
   from run import app
   # ... use app to do something

Upvotes: 4

Related Questions