N
N
Nikita Lubchich2014-11-05 12:31:34
Flask
Nikita Lubchich, 2014-11-05 12:31:34

How to properly include imports in Flask?

There is the following project structure:

  • app
    • __init__.py
    • items.py
    • REST
      • __init__.py
      • books.py






app/__init__.py
from app.REST import mod_books

app = Flask(__name__)
db = SQLAlchemy(app)

app.register_blueprint(mod_books, url_prefix='/books')


app/REST/__init__.py
mod_books = Blueprint("books", __name__)
books_api = restful.Api(mod_books)

from app.REST import books


app/REST/books.py
from app.REST import books_api
from app import db
from app.items import Book, Author

...
class BooksListApi(Resource):
...
books_api.add_resource(BooksListApi, '/')
...


In a nutshell: there is a db object in app, a blueprint is declared in app.REST , which is imported and connected to app

I need to access from app.REST.books to the db object from app in order to work with the database.

How can this structure be properly formatted so that there are no cyclic dependencies?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Teivaz, 2014-11-13
@Teivaz

I just ran into this problem yesterday.
It is enough to write in one place not from A import B, but from A import *, for example, in REST/books.py:
from app import *

Y
ykalchevskiy, 2014-11-13
@ykalchevskiy

Look towards these repositories:
https://github.com/sloria/cookiecutter-flask
https://github.com/imwilsonxu/fbone
They have a more complex project structure, but also more convenient. Logically separated: creating an app, creating extensions, registering Blueprints and extensions, and more. Look in the "app.py" files. At first it may seem like an overhead, but believe me, it is almost certain that your project will grow, new parts will be added, but this structure will remain unchanged, and the project will look harmonious and understandable.
The first repository is especially good because it is a cookiecutter template ( https://github.com/audreyr/cookiecutter).If you have not come across this application, then be sure to try it, as it can greatly simplify the creation of the initial structure of projects.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question