From 70abd78e5510c4f320d4b8d455fcef8efb5909c2 Mon Sep 17 00:00:00 2001 From: Jeff Widman Date: Mon, 9 Mar 2020 09:55:40 -0700 Subject: [PATCH] Setup DB properly When I switched over to `flask run` entrypoint in b92391d177e3abb322e31646870abac46a1f6276, I forgot that the `if name==__main__` code no longer triggers. So the SQLite in-memory database wasn't getting created for the example app. This moves the DB creation to a werkzeug/Flask hook that runs before the first request to the app, so that the DB table is created when we query it. Also updated the test which worked fine previously, but this is more idiomatic. --- example/app.py | 10 +++++----- test/basic_app.py | 6 +++++- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/example/app.py b/example/app.py index a758d44..f264250 100644 --- a/example/app.py +++ b/example/app.py @@ -29,6 +29,11 @@ class ExampleModel(db.Model): value = db.Column(db.String(100), primary_key=True) +@app.before_first_request +def setup(): + db.create_all() + + @app.route('/') def index(): app.logger.info("Hello there") @@ -38,11 +43,6 @@ def index(): @app.route('/redirect') def redirect_example(): - response = redirect(url_for('index')) response.set_cookie('test_cookie', '1') return response - - -if __name__ == "__main__": - db.create_all() diff --git a/test/basic_app.py b/test/basic_app.py index 085bf6c..e027a5b 100644 --- a/test/basic_app.py +++ b/test/basic_app.py @@ -23,8 +23,12 @@ class Foo(db.Model): id = db.Column(db.Integer, primary_key=True) +@app.before_first_request +def setup(): + db.create_all() + + @app.route('/') def index(): - db.create_all() Foo.query.filter_by(id=1).all() return render_template('basic_app.html')