0

I'm trying to passing the flask app context with some global variable to the nested api context.

run.py <= Start the flask application via app.run()
    app/
       __init__.py
       api/
          __init__.py
          controllers.py

app/__init__.py

from flask import Flask
from app.api.controllers import api

app = Flask(__name__)
app.register_blueprint(api, url_prefix='/api')

main_dict = {"a":"info1", "b":"info2}

app/api/controllers.py

from flask import Blueprint, jsonify
from app import app, main_dict

api = Blueprint('api', __name__)

@api.route('/')
def test():
    return jsonify({"status":"OK"})

It throws the following error message:

ImportError: cannot import name 'app'

Thanks!

NetBlocker
  • 11
  • 5

1 Answers1

0

You've created a circular dependency.

app wants to import app.api.controllers, but that wants to import from app. What you should do to fix it, is to create a new module containing main_dict and import that in both app and app.api.controllers:

# app/__init__.py
from .main_dict import main_dict
from .api.controllers import api

# app/main_dict.py
main_dict = {'a': 'A'}

# app/api/__init__.py

# app/api/controllers.py
from flask import current_app as app
from ..main_dict import main_dict

if you need access to the app outside of app/__init__.py, the recommended way to get at it is to use from flask import current_app

Brian
  • 555
  • 4
  • 18
  • Another solution would be to just move the assignment of `main_dict` above `from app.api.controllers import api`. – Blender Mar 12 '18 at 00:29
  • @Blender Yes, true. But I've always been taught it was generally considered poor form to put imports anywhere except at the top, above your code? – Brian Mar 12 '18 at 00:35
  • @NetBlocker Sorry, see my edit. (Python modules are referenced by their name without the `.py` extension) – Brian Mar 12 '18 at 00:40