V
V
vithar2021-08-02 15:20:19
Flask
vithar, 2021-08-02 15:20:19

What is the correct way to split a flask application into modules?

Good day to all!
When trying to make a large web application in flask, there was some problem when dividing the application into different files.
There is an app.py file which contains the following content:

app = Flask(__name__)
engine = create_engine(config.SQLALCHEMY_DATABASE_URI)
Base = declarative_base()
Session = sessionmaker(bind=engine)
session = Session()
if __name__ == '__main__':
    app.run(debug=True

in an entity file called user.py:
class User(Base):
    __tablename__ = 'payments'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    surname = Column(String)
    second_name = Column(String)

and finally in the file with mappings (MapTest.py) is:
@map_test.route('/test')
def test():
    user = User()
    user.name = 'name'
    user.surname = 'sname'
    session.add(user)
    return Utils.getAnswer('ok')

Utils, if that generates a response.

When trying to import into user.py And then into MapTest.py
from app import Base
from app import session
from entities.User import User

An ImportError occurs because dependencies are looping
. Trying to use BluePrint didn't work in this situation.

In general, my question is even more global. How to organize the structure of a flask application? To make it just like in spring, everything is in directories, files, etc. Searches on the Internet did not give a positive result in all manuals for flask everything is done in one file.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ruslan Gilfanov, 2021-08-09
@ri_gilfanov

Take the following out of it app.pyinto a separate file (for example, base/orm.py):

engine = create_engine(config.SQLALCHEMY_DATABASE_URI)
Base = declarative_base()
Session = sessionmaker(bind=engine)
session = Session()

And then import these objects where they are used.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question