Backend development with Flask: Using Flask's app factory pattern (+22, -18)
app.py (+22, -18)
From:
curriculum/section07/lectures/16_flask_app_factory_pattern/start/app.py
To:
curriculum/section07/lectures/16_flask_app_factory_pattern/end/app.py
index ec0910f..05fde93 100644
--- a/curriculum/section07/lectures/16_flask_app_factory_pattern/start/app.py
+++ b/curriculum/section07/lectures/16_flask_app_factory_pattern/end/app.py
@@ -7,24 +7,28 @@ from dotenv import load_dotenv
load_dotenv()
-app = Flask(__name__)
-client = MongoClient(os.getenv("MONGODB_URI"))
-app.db = client.microblog
+def create_app():
+ app = Flask(__name__)
+ client = MongoClient(os.getenv("MONGODB_URI"))
+ app.db = client.microblog
+ @app.route("/", methods=["GET", "POST"])
+ def home():
+ if request.method == "POST":
+ entry_content = request.form.get("content")
+ formatted_date = datetime.datetime.today().strftime("%Y-%m-%d")
+ app.db.entries.insert_one(
+ {"content": entry_content, "date": formatted_date}
+ )
-@app.route("/", methods=["GET", "POST"])
-def home():
- if request.method == "POST":
- entry_content = request.form.get("content")
- formatted_date = datetime.datetime.today().strftime("%Y-%m-%d")
- app.db.entries.insert_one({"content": entry_content, "date": formatted_date})
+ entries_with_date = [
+ (
+ entry["content"],
+ entry["date"],
+ datetime.datetime.strptime(entry["date"], "%Y-%m-%d").strftime("%b %d"),
+ )
+ for entry in app.db.entries.find({})
+ ]
+ return render_template("home.html", entries=entries_with_date)
- entries_with_date = [
- (
- entry["content"],
- entry["date"],
- datetime.datetime.strptime(entry["date"], "%Y-%m-%d").strftime("%b %d"),
- )
- for entry in app.db.entries.find({})
- ]
- return render_template("home.html", entries=entries_with_date)
+ return app