Flask – Bad Practices 1

The reason of direct instantiate object SQLAlchemy may cause unexpected result to reflect your data. For instance if you’ve configure the following idiom, It will caused the result that not reflect from your database.

def create_app(config_filename):
    app = Flask(__name__)
    app.config.from_pyfile(config_filename)

    db = SQLAlchemy(app)

 

The recommended way is define the object and pass the app object to init_app function.

db = SQLAlchemy()

def create_app(config_filename):
    app = Flask(__name__)
    cfg = os.path.join(os.getcwd(), 'config', config_name + '.py')
    app.config.from_pyfile(cfg)

    db.init_app(app)
    .....

 

Next, I’ll demo through the animation to show you how badly the problem may caused.

  1. By using the mention idiom, when database value is directly modified, the application value has no changes.
  2. After that, I made the code changed to recommended way, it produce the result expectedly.

 

 

Reference:

http://flask.pocoo.org/docs/0.12/patterns/appfactories/

Flask – Bad Practices 1

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.