How to structure a Flask application like in Django?

I switched from Django to Flask for the project and lost a bit how to set up the same structure as in Django.

In my checkbox example, everything works fine in a single file, but at the moment when I even try to output models to my class, I ran into a cross-reference problem and cannot solve it.

F11.py

app = Flask(__name__) db = SQLAlchemy(app) ... if __name__ == "__main__": app.run() 

models.py

 class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) password = db.Column(db.String) 

The problem already starts with db.Model . db is created mainly by F11.py , so how do I get it? If I just import it, I get a cross-link error.

+4
source share
2 answers

I usually put initializations in __init__.py in the main project folder.

__init__.py

 app = Flask(__name__) db = SQLAlchemy(app) import myproject.views import myproject.models 

models.py

 from myproject import app from myproject import db class User(db.Model): 

runserver.py (one level up)

 from myproject import app app.run(debug=True) 
+1
source

In general, I like to structure my application in such a way that you do not need an import app in any of the files. For my current project, the only file that the application imports is a file called manage.py , which does a little more than allows me to do certain things using Flask-Script.

A good feature that many Flask extensions have is the init_app method. This allows you to instantiate applications without requiring an application.

Say you created a database called db in a file called db.py It might look something like this:

 from flask.ext.sqlalchemy import SQLAlchemy db = SQLAlchemy() 

Let's say you configured the application in __init__.py . This file might look something like

 from flask import Flask from app.db import db app = Flask(__name__) db.init_app(app) # ... 

Now your database is initialized for your Flask application, and you will not have problems with a circular reference when you import db directly through from app.db import db , for example, in models.py .

For my views, I often return to drawings instead of using @app.route('/') methods. As in the database, drawings can simply be imported into your __init__.py file and registered in the application there.

+2
source

Source: https://habr.com/ru/post/1484297/


All Articles