3
\$\begingroup\$

I have a simple Flask app that realises rest-api with SQLAlchemy. I have written this create_app function:

views.py

def create_app(config):
   app.config.from_object(config)
   url = config.DATABASE_URI
   engine = create_engine(url)
   Base.metadata.create_all(engine)

   Base.metadata.bind = engine
   DBSession = sessionmaker(bind=engine)
   session = DBSession()
   app.db_session = session
   return app

and a typical view looks like:

views.py

@app.route('/restaurants', methods=['GET', 'POST'])
def all_restaurants_handler():
    if request.method == 'GET':
        # RETURN ALL RESTAURANTS IN DATABASE
        restaurants = app.db_session.query(Restaurant).all()
        return jsonify(restaurants=[i.serialize for i in restaurants])

So, when I write tests, I can pass to create_app function test configuration. Although this works, I have some doubts regarding design of this solution. First of all, I don't like that I need to use app.db_session in order to get the session. Second, I am not sure if it's a good decision to initialize db in the create_app function.

\$\endgroup\$

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.