Skip to content

Commit

Permalink
feat: finish app page
Browse files Browse the repository at this point in the history
  • Loading branch information
Darkflame72 committed Mar 30, 2024
1 parent 9ec9821 commit 7b37727
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 59 deletions.
106 changes: 48 additions & 58 deletions src/content/docs/guides/python/flask/app.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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()
```

<Steps>

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.

</Steps>

In the `__init__.py` file, import the `db` module and call the `init_app` function.

```diff lang="python"
Expand All @@ -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.
2 changes: 1 addition & 1 deletion src/content/docs/guides/python/flask/database.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down

0 comments on commit 7b37727

Please sign in to comment.