| 1 |
.. _blog_tutorial: |
| 2 |
|
| 3 |
Tutorial: Building a simple blog |
| 4 |
================================ |
| 5 |
|
| 6 |
In this tutorial we will build a simple blog with entries stored in a |
| 7 |
database. We'll then render these posts on the server and serve the |
| 8 |
HTML directly to the user. |
| 9 |
|
| 10 |
This tutorial is meant to serve as an introduction to building server |
| 11 |
rendered websites in Quart. If you want to skip to the end the code is |
| 12 |
on `Github <https://github.com/pallets/quart/tree/main/examples/blog>`_. |
| 13 |
|
| 14 |
1: Creating the project |
| 15 |
----------------------- |
| 16 |
|
| 17 |
We need to create a project for our blog server, I like to use |
| 18 |
`Poetry <https://python-poetry.org>`_ to do this. Poetry is installed |
| 19 |
via pip (or via `Brew <https://brew.sh/>`_): |
| 20 |
|
| 21 |
.. code-block:: console |
| 22 |
|
| 23 |
pip install poetry |
| 24 |
|
| 25 |
We can then use Poetry to create a new blog project: |
| 26 |
|
| 27 |
.. code-block:: console |
| 28 |
|
| 29 |
poetry new --src blog |
| 30 |
|
| 31 |
Our project can now be developed in the *blog* directory, and all |
| 32 |
subsequent commands should be in run the *blog* directory. |
| 33 |
|
| 34 |
2: Adding the dependencies |
| 35 |
-------------------------- |
| 36 |
|
| 37 |
To start we only need Quart to build the blog server, which we can |
| 38 |
install as a dependency of the project by running the following: |
| 39 |
|
| 40 |
.. code-block:: console |
| 41 |
|
| 42 |
poetry add quart |
| 43 |
|
| 44 |
Poetry will ensure that this dependency is present and the paths are |
| 45 |
correct by running: |
| 46 |
|
| 47 |
.. code-block:: console |
| 48 |
|
| 49 |
poetry install |
| 50 |
|
| 51 |
3: Creating the app |
| 52 |
------------------- |
| 53 |
|
| 54 |
We need a Quart app to be our web server, which is created by the |
| 55 |
following addition to *src/blog/__init__.py*: |
| 56 |
|
| 57 |
.. code-block:: python |
| 58 |
:caption: src/blog/__init__.py |
| 59 |
|
| 60 |
from quart import Quart |
| 61 |
|
| 62 |
app = Quart(__name__) |
| 63 |
|
| 64 |
def run() -> None: |
| 65 |
app.run() |
| 66 |
|
| 67 |
To make the app easy to run we can call the run method from a poetry |
| 68 |
script, by adding the following to *pyproject.toml*: |
| 69 |
|
| 70 |
.. code-block:: toml |
| 71 |
:caption: pyproject.toml |
| 72 |
|
| 73 |
[tool.poetry.scripts] |
| 74 |
start = "blog:run" |
| 75 |
|
| 76 |
Which allows the following command to start the app: |
| 77 |
|
| 78 |
.. code-block:: console |
| 79 |
|
| 80 |
poetry run start |
| 81 |
|
| 82 |
4: Creating the database |
| 83 |
------------------------ |
| 84 |
|
| 85 |
There are many database management systems to choose from depending |
| 86 |
upon the needs and requirements. In this case we need only the |
| 87 |
simplest system, and Python’s standard library includes SQLite making |
| 88 |
it the easiest. |
| 89 |
|
| 90 |
To initialise the database we need the following SQL to create the |
| 91 |
correct table, as added to *src/blog/schema.sql*: |
| 92 |
|
| 93 |
.. code-block:: sql |
| 94 |
:caption: src/blog/schema.sql |
| 95 |
|
| 96 |
DROP TABLE IF EXISTS post; |
| 97 |
CREATE TABLE post ( |
| 98 |
id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 99 |
title TEXT NOT NULL, |
| 100 |
'text' TEXT NOT NULL |
| 101 |
); |
| 102 |
|
| 103 |
Next we need to be able to create the database on command, which |
| 104 |
we can do by adding the command code to *src/blog/__init__.py*: |
| 105 |
|
| 106 |
.. code-block:: python |
| 107 |
:caption: src/blog/__init__.py |
| 108 |
|
| 109 |
from pathlib import Path |
| 110 |
from sqlite3 import dbapi2 as sqlite3 |
| 111 |
|
| 112 |
app.config.update({ |
| 113 |
"DATABASE": Path(app.root_path) / "blog.db", |
| 114 |
}) |
| 115 |
|
| 116 |
def _connect_db(): |
| 117 |
engine = sqlite3.connect(app.config["DATABASE"]) |
| 118 |
engine.row_factory = sqlite3.Row |
| 119 |
return engine |
| 120 |
|
| 121 |
def init_db(): |
| 122 |
db = _connect_db() |
| 123 |
with open(Path(app.root_path) / "schema.sql", mode="r") as file_: |
| 124 |
db.cursor().executescript(file_.read()) |
| 125 |
db.commit() |
| 126 |
|
| 127 |
Next we need to update the poetry scripts in *pyproject.toml* to be: |
| 128 |
|
| 129 |
.. code-block:: toml |
| 130 |
:caption: pyproject.toml |
| 131 |
|
| 132 |
[tool.poetry.scripts] |
| 133 |
init_db = "blog:init_db" |
| 134 |
start = "blog:run" |
| 135 |
|
| 136 |
Now we can run the following to create and update the database: |
| 137 |
|
| 138 |
.. code-block:: console |
| 139 |
|
| 140 |
poetry run init_db |
| 141 |
|
| 142 |
.. warning:: |
| 143 |
|
| 144 |
Running this command will wipe any existing data. |
| 145 |
|
| 146 |
|
| 147 |
5: Displaying posts in the database |
| 148 |
----------------------------------- |
| 149 |
|
| 150 |
With can now display the posts present in the database. To do so we |
| 151 |
first need a template to render the posts as HTML. This is as follows |
| 152 |
and should be added to *src/blog/templates/posts.html*: |
| 153 |
|
| 154 |
.. code-block:: html |
| 155 |
:caption: src/blog/templates/posts.html |
| 156 |
|
| 157 |
<main> |
| 158 |
{% for post in posts %} |
| 159 |
<article> |
| 160 |
<h2>{{ post.title }}</h2> |
| 161 |
<p>{{ post.text|safe }}</p> |
| 162 |
</article> |
| 163 |
{% else %} |
| 164 |
<p>No posts available</p> |
| 165 |
{% endfor %} |
| 166 |
</main> |
| 167 |
|
| 168 |
Now we need a route to query the database, retrieve the messages, |
| 169 |
and render the template. As done with the following code which should |
| 170 |
be added to *src/blog/__init__.py*: |
| 171 |
|
| 172 |
.. code-block:: python |
| 173 |
:caption: src/blog/__init__.py |
| 174 |
|
| 175 |
from quart import render_template, g |
| 176 |
|
| 177 |
def _get_db(): |
| 178 |
if not hasattr(g, "sqlite_db"): |
| 179 |
g.sqlite_db = _connect_db() |
| 180 |
return g.sqlite_db |
| 181 |
|
| 182 |
@app.get("/") |
| 183 |
async def posts(): |
| 184 |
db = _get_db() |
| 185 |
cur = db.execute( |
| 186 |
"""SELECT title, text |
| 187 |
FROM post |
| 188 |
ORDER BY id DESC""", |
| 189 |
) |
| 190 |
posts = cur.fetchall() |
| 191 |
return await render_template("posts.html", posts=posts) |
| 192 |
|
| 193 |
6: Creating a new post |
| 194 |
---------------------- |
| 195 |
|
| 196 |
To create blog posts we first need a form into which a user can enter |
| 197 |
the post details. This is done via the following template code that should |
| 198 |
be added to *src/blog/templates/create.html*: |
| 199 |
|
| 200 |
.. code-block:: html |
| 201 |
:caption: src/blog/templates/create.html |
| 202 |
|
| 203 |
<form method="POST" style="display: flex; flex-direction: column; gap: 8px; max-width:400px"> |
| 204 |
<label>Title: <input type="text" size="30" name="title" /></label> |
| 205 |
<label>Text: <textarea name="text" rows="5" cols="40"></textarea></label> |
| 206 |
<button type="submit">Create</button> |
| 207 |
</form> |
| 208 |
|
| 209 |
The styling ensures that the elements of the form are arranged |
| 210 |
verically with a gap and sensible maximum width. |
| 211 |
|
| 212 |
To allow a visitor to create a blog post we need to accept the POST |
| 213 |
request generated by this form in the browser. To do so the following |
| 214 |
should be added to *src/blog/__init__.py*: |
| 215 |
|
| 216 |
.. code-block:: python |
| 217 |
:caption: src/blog/__init__.py |
| 218 |
|
| 219 |
from quart import redirect, request, url_for |
| 220 |
|
| 221 |
@app.route("/create/", methods=["GET", "POST"]) |
| 222 |
async def create(): |
| 223 |
if request.method == "POST": |
| 224 |
db = _get_db() |
| 225 |
form = await request.form |
| 226 |
db.execute( |
| 227 |
"INSERT INTO post (title, text) VALUES (?, ?)", |
| 228 |
[form["title"], form["text"]], |
| 229 |
) |
| 230 |
db.commit() |
| 231 |
return redirect(url_for("posts")) |
| 232 |
else: |
| 233 |
return await render_template("create.html") |
| 234 |
|
| 235 |
This route handler will render the creation form in response to a GET |
| 236 |
request e.g. via navigation in the browser. However, for a POST |
| 237 |
request it will extract the form data to create a blog post before |
| 238 |
redirecting the user to the page with the posts. |
| 239 |
|
| 240 |
7: Testing |
| 241 |
---------- |
| 242 |
|
| 243 |
To test our app we need to check that a blog post can be created, and |
| 244 |
once done so shows on the posts page. Firstly we need to create a |
| 245 |
temporary database for testing, which we can do using a pytest fixture |
| 246 |
placed in *tests/conftest.py*: |
| 247 |
|
| 248 |
.. code-block:: python |
| 249 |
:caption: tests/conftest.py |
| 250 |
|
| 251 |
import pytest |
| 252 |
|
| 253 |
from blog import app, init_db |
| 254 |
|
| 255 |
@pytest.fixture(autouse=True) |
| 256 |
def configure_db(tmpdir): |
| 257 |
app.config['DATABASE'] = str(tmpdir.join('blog.db')) |
| 258 |
init_db() |
| 259 |
|
| 260 |
This fixture will run automatically before our tests, thereby setting up |
| 261 |
a database we can use in the tests. |
| 262 |
|
| 263 |
To test the creation and display we can add the following to |
| 264 |
*tests/test_blog.py*: |
| 265 |
|
| 266 |
.. code-block:: python |
| 267 |
:caption: tests/test_blog.py |
| 268 |
|
| 269 |
from blog import app |
| 270 |
|
| 271 |
async def test_create_post(): |
| 272 |
test_client = app.test_client() |
| 273 |
response = await test_client.post("/create/", form={"title": "Post", "text": "Text"}) |
| 274 |
assert response.status_code == 302 |
| 275 |
response = await test_client.get("/") |
| 276 |
text = await response.get_data() |
| 277 |
assert b"<h2>Post</h2>" in text |
| 278 |
assert b"<p>Text</p>" in text |
| 279 |
|
| 280 |
As the test is an async function we need to install `pytest-asyncio |
| 281 |
<https://github.com/pytest-dev/pytest-asyncio>`_ by running the |
| 282 |
following: |
| 283 |
|
| 284 |
.. code-block:: console |
| 285 |
|
| 286 |
poetry add --dev pytest-asyncio |
| 287 |
|
| 288 |
Once installed it needs to be configured by adding the following to |
| 289 |
*pyproject.toml*: |
| 290 |
|
| 291 |
.. code-block:: toml |
| 292 |
|
| 293 |
[tool.pytest.ini_options] |
| 294 |
asyncio_mode = "auto" |
| 295 |
|
| 296 |
Finally we can run the tests via this command: |
| 297 |
|
| 298 |
.. code-block:: console |
| 299 |
|
| 300 |
poetry run pytest tests/ |
| 301 |
|
| 302 |
If you are running this in the Quart example folder you'll need to add |
| 303 |
a ``-c pyproject.toml`` option to prevent pytest from using the Quart |
| 304 |
pytest configuration. |
| 305 |
|
| 306 |
8: Summary |
| 307 |
---------- |
| 308 |
|
| 309 |
We've built a simple database backed blog server. This should be a |
| 310 |
good starting point to building any type of server rendered app. |