From 7b3772716c692f2beb58dcaa384f0c3db75026a7 Mon Sep 17 00:00:00 2001 From: Leon Bowie Date: Sun, 31 Mar 2024 02:32:53 +1300 Subject: [PATCH] feat: finish app page --- src/content/docs/guides/python/flask/app.mdx | 106 ++++++++---------- .../docs/guides/python/flask/database.mdx | 2 +- 2 files changed, 49 insertions(+), 59 deletions(-) diff --git a/src/content/docs/guides/python/flask/app.mdx b/src/content/docs/guides/python/flask/app.mdx index 13ebf0dd..c2c8e530 100644 --- a/src/content/docs/guides/python/flask/app.mdx +++ b/src/content/docs/guides/python/flask/app.mdx @@ -147,34 +147,55 @@ Update the `__init__.py` file to register the blueprint. return "pong!" ``` -## Setting up the db +## Setting up the database -Create a new file called `db.py` and add the following code to it. +Following from how we set up the blog blueprint, we can create a new file called `db.py` and add the following code to it. ```python // flaskapp/db.py -import sqlite3 -from flask import current_app, g, Flask +from flask import Flask +from flask_sqlalchemy import SQLAlchemy +from sqlalchemy.orm import DeclarativeBase -def get_db(): - """Get a new database connection. If one already exists, use that one.""" - if 'db' not in g: - g.db = sqlite3.connect(current_app.config["DATABASE"]) - g.db.row_factory = sqlite3.Row - return g.db +class Base(DeclarativeBase): + pass -def close_db(e=None): - """Close the database connection if it exists.""" - db = g.pop("db") +db = SQLAlchemy(model_class=Base) - if db is not None: - db.close() +class Post(db.Model): + id = db.Column(db.Integer, primary_key=True) + title = db.Column(db.String(100), nullable=False) + content = db.Column(db.Text, nullable=False) def init_app(app: Flask): - """Register the close_db function with the Flask app.""" - app.teardown_appcontext(close_db) + db.init_app(app) + with app.app_context(): + db.create_all() ``` + + +1. The `Base` class is created as a base for the databases + +2. The `db` object is created + + The `db` object is created using the `SQLAlchemy` class. + The `model_class` parameter is set to the `Base` class to use it as the base for all models. + +3. The `Post` model is created + + The `Post` model is created with an `id`, `title`, and `content` column. + The `id` column is the primary key. + The `title` and `content` columns are set to be not nullable. + +4. The `init_app` function is created + + The `init_app` function is created to initialise the database. + The `db` object is initialised with the app. + The database is created with the `create_all` method. + + + In the `__init__.py` file, import the `db` module and call the `init_app` function. ```diff lang="python" @@ -190,49 +211,18 @@ In the `__init__.py` file, import the `db` module and call the `init_app` functi app.register_blueprint(blog) ``` -## Database Setup - -While we have the database setup we need to create the tables. We can do this by creating a new file called `schema.sql`. - -```sql -// flaskapp/schema.sql -DROP TABLE IF EXISTS post; -CREATE TABLE post ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - title TEXT NOT NULL, - body TEXT NOT NULL -); -``` - - +With the database set up, we can now add a route to add a post to the database. ```diff lang="python" -// flaskapp/__init__.py -+def init_db(): -+ """Create and fill the db.""" -+ db = get_db() -+ -+ with current_app.open_resource("schema.sql") as f: -+ db.executescript(f.read().decode("utf8")) - - -+@click.command("init-db") -+def init_db_command(): -+ """Clear the existing data and create new tables.""" -+ init_db() -+ click.echo("Initialized the database.") - -def init_app(app): - """Add teardown and cli on app creation.""" - app.teardown_appcontext(close_db) -+ app.cli.add_command(init_db_command) -``` +// flaskapp/blog.py ++ from .db import Post, db -As we have now integrated our database into our app we can now initialise it. To do this we can run the following command: +... -```bash -$ flask --app flaskapp init-db -Initialized the database. ++@bp.route("/add_post") ++def add_post(): ++ post = Post(title="Hello World", content="This is my first post") ++ db.session.add(post) ++ db.session.commit() ++ return "Post added" ``` - -You should now be able to see a flaskapp.sqlite file in the instance folder in your project which is your newly created database. diff --git a/src/content/docs/guides/python/flask/database.mdx b/src/content/docs/guides/python/flask/database.mdx index 633f7085..27ceee55 100644 --- a/src/content/docs/guides/python/flask/database.mdx +++ b/src/content/docs/guides/python/flask/database.mdx @@ -235,7 +235,7 @@ db.session.commit() #### Using SQLAlchemy to setup the database -We can also use SQLAlchemy to create the database and tables for us. We can use the `create_all` method to create the tables: +We can also use SQLAlchemy to create the database and tables for us. We can use the `create_all` method to create the tables. If the tables already exist, this method will not do anything. ```python with app.app_context():