In one sentence
With Oxyde, a Python ORM, in this part we make writes that touch several rows at once safe, learn to recognize the tool’s errors, and put the mini blog behind a small web API. The goal is to make sure a group of database changes is either all saved or not saved at all, and to let a browser or another program read the articles.
Where we left off
In part 1 we installed Oxyde 0.9.0, a Python ORM, defined the models Author and Post, which are the Python classes that describe the tables, and created the tables with migrations, meaning the instructions that build and change them. In part 2 we filled the blog with 3 authors and 8 articles, and learned how to query it with filters, joins (which combine the data of two tables) and aggregations (calculations such as counts over groups of rows).
This part continues the same project: if you are arriving here, you must have done the previous parts.
What we’ll do in this part with Oxyde
In this part we make operations that write several rows together safe, using transactions. We learn to recognize Oxyde’s exceptions, which are error signals with a precise name, and to handle them in the right place. Then we publish the mini blog as a small web API with FastAPI, with also a simple HTML page, the language of web pages, with the list of articles. Everything is tested with real requests, and at the end you will find an honest verdict on when it is worth using.
By the end you will have:
- A function that creates an author and their article in a single transaction, and that cancels everything if something goes wrong.
- The ability to recognize the tool’s common exceptions and to understand where to handle them.
- An API with FastAPI that lists, shows and creates articles.
- A 404 response, instead of a 500 error, when an article does not exist.
- An HTML page with the latest articles of the mini blog, to look at in the browser.
What you need
You need a terminal and Python 3.10 or higher: the steps were tested with 3.11. You also need the project from the previous parts, with the virtual environment created in part 1, which is an isolated Python folder that holds the project’s packages, still active in the terminal. You don’t need keys or accounts.
Step by step
Step 3.1: I create an author and their article in a transaction
A transaction groups several writes: either they are all confirmed, or they are all cancelled. You write async with transaction.atomic():, and everything inside the block is part of the transaction. If the block ends without errors, the changes are confirmed automatically when it exits. The file conteggi.py contains a function that counts authors and articles: we will use it throughout this part to check the effect of each operation on the database. Here the block ends well, so we find one more author and one more article.
File conteggi.py:
from models import Author, Post
async def conteggi():
"""Return the number of authors and posts as a short text."""
return f"{await Author.objects.count()} autori, {await Post.objects.count()} articoli"
File transazione_ok.py:
import asyncio
from oxyde import db
from oxyde.db import transaction
from conteggi import conteggi
from models import Author, Post
from oxyde_config import DATABASES
async def main():
async with db.connect(DATABASES["default"]):
print("prima:", await conteggi())
async with transaction.atomic():
dario = await Author.objects.create(name="Dario Neri", email="dario@example.com")
await Post.objects.create(
title="Il mio primo articolo", content="Ciao a tutti!", published=True, author_id=dario.id
)
print("dopo:", await conteggi())
print("articoli di Dario:", await Post.objects.filter(author_id=dario.id).count())
if __name__ == "__main__":
asyncio.run(main())
python transazione_ok.py
Output:
prima: 3 autori, 8 articoli
dopo: 4 autori, 9 articoli
articoli di Dario: 1
In the output you see three lines: first 3 authors and 8 articles, then 4 authors and 9 articles, and 1 article for Dario. If your numbers are the same, the author and the article were confirmed together.
Step 3.2: Rollback: an error halfway through also cancels the author already created
Now the function crea_autore_con_articolo creates the author, and then, before creating the article, it checks the title: if the title is empty, it raises a ValueError, a standard Python error. The error happens after the author has already been written, and the count inside the transaction shows it. Because the exception leaves the atomic() block, the transaction is cancelled: this is the rollback, and the author disappears along with everything else. The try/except that prints the error is outside the transaction, in the function main.
File transazione_errore.py:
import asyncio
from oxyde import db
from oxyde.db import transaction
from conteggi import conteggi
from models import Author, Post
from oxyde_config import DATABASES
async def crea_autore_con_articolo(nome, email, titolo):
async with transaction.atomic():
autore = await Author.objects.create(name=nome, email=email)
print(f" nella transazione: creato {autore.name}, autori ora {await Author.objects.count()}")
if not titolo.strip():
raise ValueError("il titolo dell'articolo è vuoto")
await Post.objects.create(title=titolo, content="Testo.", author_id=autore.id)
async def main():
async with db.connect(DATABASES["default"]):
print("prima:", await conteggi())
try:
await crea_autore_con_articolo("Elena Galli", "elena@example.com", " ")
except ValueError as errore:
print("errore:", errore)
print("dopo:", await conteggi())
print("Elena nel database:", await Author.objects.get_or_none(email="elena@example.com"))
if __name__ == "__main__":
asyncio.run(main())
python transazione_errore.py
Output:
prima: 4 autori, 9 articoli
nella transazione: creato Elena Galli, autori ora 5
errore: il titolo dell'articolo è vuoto
dopo: 4 autori, 9 articoli
Elena nel database: None
The line nella transazione shows 5 authors, that is, the author already written before the error. In the end the counts go back to 4 authors and 9 articles, and the search for Elena returns None, meaning no result.
Step 3.3: Savepoint: I cancel only part of the transaction
An atomic() inside another atomic() creates a savepoint: if the inner block fails, only the work done inside it is cancelled, while the work of the outer block stays valid. Here the outer block creates the author Franco; the inner block creates an article and then raises an error, which we catch right away, outside the inner block. After that, the outer block creates a second article and ends normally. The function transaction.get_transaction_depth() tells you what nesting level you are at, meaning how many blocks are one inside the other: 1 in the outer block, 2 in the inner one.
File punto_di_salvataggio.py:
import asyncio
from oxyde import db
from oxyde.db import transaction
from conteggi import conteggi
from models import Author, Post
from oxyde_config import DATABASES
async def main():
async with db.connect(DATABASES["default"]):
print("prima:", await conteggi())
async with transaction.atomic():
print("profondità nel blocco esterno:", transaction.get_transaction_depth())
franco = await Author.objects.create(name="Franco Costa", email="franco@example.com")
try:
async with transaction.atomic():
print("profondità nel blocco interno:", transaction.get_transaction_depth())
await Post.objects.create(title="Articolo da annullare", content="-", author_id=franco.id)
raise ValueError("annullo solo il blocco interno")
except ValueError as errore:
print("errore nel blocco interno:", errore)
await Post.objects.create(title="Articolo confermato", content="Testo.", author_id=franco.id)
print("dopo:", await conteggi())
titoli = await Post.objects.filter(author_id=franco.id).order_by("id").values_list("title", flat=True).all()
print("articoli di Franco:", titoli)
if __name__ == "__main__":
asyncio.run(main())
python punto_di_salvataggio.py
Output:
prima: 4 autori, 9 articoli
profondità nel blocco esterno: 1
profondità nel blocco interno: 2
errore nel blocco interno: annullo solo il blocco interno
dopo: 5 autori, 10 articoli
articoli di Franco: ['Articolo confermato']
In the output the depth is 1 in the outer block and 2 in the inner block. In the end Franco is in the database with only the confirmed article, and the counts are 5 authors and 10 articles.
Step 3.4: I recognize Oxyde’s exceptions
When an operation cannot succeed, Oxyde raises an exception with a precise name, and all the exceptions come from OxydeError: by catching that one, you handle any error from the tool. The function prova runs an operation and, if it fails, prints the name of the exception’s class and the message. get() raises NotFoundError if it finds nothing, and MultipleObjectsReturned if it finds more than one row. An email that is already in use breaks the db_unique constraint and raises UniqueViolationError, which is a kind of IntegrityError; errors in the query itself, such as a field that does not exist, also have their own exception.
File eccezioni.py:
import asyncio
from oxyde import IntegrityError, NotFoundError, OxydeError, UniqueViolationError, db
from conteggi import conteggi
from models import Author, Post
from oxyde_config import DATABASES
async def prova(descrizione, operazione):
try:
await operazione()
print(f"{descrizione}: nessun errore")
except OxydeError as errore:
print(f"{descrizione}: {type(errore).__name__} | {errore}")
async def main():
async with db.connect(DATABASES["default"]):
await prova("get(id=999)", lambda: Post.objects.get(id=999))
await prova("get(published=True)", lambda: Post.objects.get(published=True))
await prova("email già usata", lambda: Author.objects.create(name="Alice Due", email="alice@example.com"))
await prova("campo inesistente", lambda: Post.objects.filter(voti=1).all())
await prova("valore sbagliato per __in", lambda: Post.objects.filter(id__in="1").all())
print("UniqueViolationError è un IntegrityError?", issubclass(UniqueViolationError, IntegrityError))
print("NotFoundError è un OxydeError?", issubclass(NotFoundError, OxydeError))
print("nel database:", await conteggi())
if __name__ == "__main__":
asyncio.run(main())
python eccezioni.py
Output:
get(id=999): NotFoundError | Post matching query not found
get(published=True): MultipleObjectsReturned | Query for Post returned multiple objects
email già usata: UniqueViolationError | Query execution error: Query failed: error returned from database: (code: 2067) UNIQUE constraint failed: authors.email
campo inesistente: FieldError | Post has no field 'voti'
valore sbagliato per __in: FieldLookupValueError | Lookup 'in' does not accept string values; use a sequence
UniqueViolationError è un IntegrityError? True
NotFoundError è un OxydeError? True
nel database: 5 autori, 10 articoli
The last three lines confirm that UniqueViolationError is an IntegrityError and that NotFoundError is an OxydeError (both checks give True), and that the database is still at 5 authors and 10 articles.
Step 3.5: Common mistake: I catch the exception inside transaction.atomic()
This version of crea_autore_con_articolo looks more careful: it handles the error with try/except directly inside the transaction. But this way the exception never leaves the atomic() block, which ends normally and confirms what was written: the author Giulia stays in the database without her article. The program shows this by counting the authors before and after, and it ends with an assert (a check that must turn out true) that expects the same number of authors: the check fails.
Now we cause the error on purpose, to see what really happens.
File errore_comune.py:
import asyncio
from oxyde import db
from oxyde.db import transaction
from models import Author, Post
from oxyde_config import DATABASES
async def crea_autore_con_articolo(nome, email, titolo):
async with transaction.atomic():
autore = await Author.objects.create(name=nome, email=email)
try:
if not titolo.strip():
raise ValueError("il titolo dell'articolo è vuoto")
await Post.objects.create(title=titolo, content="Testo.", author_id=autore.id)
except ValueError as errore:
# WRONG: the exception is handled inside the transaction, so no rollback happens
print("errore gestito:", errore)
async def main():
async with db.connect(DATABASES["default"]):
autori_prima = await Author.objects.count()
print("autori prima:", autori_prima)
await crea_autore_con_articolo("Giulia Russo", "giulia@example.com", " ")
autori_dopo = await Author.objects.count()
print("autori dopo:", autori_dopo)
giulia = await Author.objects.get(email="giulia@example.com")
print("articoli di Giulia:", await Post.objects.filter(author_id=giulia.id).count())
assert autori_dopo == autori_prima, (
f"autori: attesi {autori_prima}, trovati {autori_dopo} (Giulia Russo salvata senza articoli)"
)
if __name__ == "__main__":
asyncio.run(main())
python errore_comune.py > uscita.txt 2> errore.txt
codice=$?
cat uscita.txt
tail -n 1 errore.txt
echo "codice di uscita: $codice"
(exit "$codice")
Output:
autori prima: 5
errore gestito: il titolo dell'articolo è vuoto
autori dopo: 6
articoli di Giulia: 0
AssertionError: autori: attesi 5, trovati 6 (Giulia Russo salvata senza articoli)
codice di uscita: 1
In the output the authors go from 5 to 6, and Giulia is saved with 0 articles. The message that starts with AssertionError is the error from the check: it says the expected number of authors was 5 and the number found was 6. The last line shows the code 1, which usually means a program ended with an error; this error is intentional, and it is the demonstration of the problem.
Step 3.6: Fix: I handle the exception outside the transaction
First we remove the author left half-done in the previous step, with filter(...).delete(). Then we use the corrected version of the function: inside atomic() there is no try, so the exception goes through the block and cancels everything, while the try/except is in main, outside the transaction. Finally we try again with a valid title: this time the author and the article are saved together.
File correzione.py:
import asyncio
from oxyde import db
from oxyde.db import transaction
from conteggi import conteggi
from models import Author, Post
from oxyde_config import DATABASES
async def crea_autore_con_articolo(nome, email, titolo):
async with transaction.atomic():
autore = await Author.objects.create(name=nome, email=email)
if not titolo.strip():
raise ValueError("il titolo dell'articolo è vuoto")
await Post.objects.create(title=titolo, content="Testo.", author_id=autore.id)
return autore
async def main():
async with db.connect(DATABASES["default"]):
cancellati = await Author.objects.filter(email="giulia@example.com").delete()
print("autori rimasti a metà cancellati:", cancellati)
print("prima:", await conteggi())
try:
await crea_autore_con_articolo("Giulia Russo", "giulia@example.com", " ")
except ValueError as errore:
print("errore gestito fuori dalla transazione:", errore)
print("dopo il tentativo fallito:", await conteggi())
print("Giulia nel database:", await Author.objects.get_or_none(email="giulia@example.com"))
await crea_autore_con_articolo("Giulia Russo", "giulia@example.com", "Finalmente online")
print("con un titolo valido:", await conteggi())
if __name__ == "__main__":
asyncio.run(main())
python correzione.py
Output:
autori rimasti a metà cancellati: 1
prima: 5 autori, 10 articoli
errore gestito fuori dalla transazione: il titolo dell'articolo è vuoto
dopo il tentativo fallito: 5 autori, 10 articoli
Giulia nel database: None
con un titolo valido: 6 autori, 11 articoli
After the failed attempt, the counts go back to 5 authors and 10 articles, and Giulia is not in the database. The last line, with a valid title, shows 6 authors and 11 articles: the author and the article were saved together.
Step 3.7: I install FastAPI and Uvicorn at fixed versions
FastAPI is the framework we use to write the web API, and Uvicorn is the server that runs it and answers the requests. As in part 1, we fix the exact versions with ==, so the commands in this tutorial give the same results. The installation happens inside the virtual environment, which is still active. Then we check the installed versions with pip show, including the version of the tool, which must not change.
pip install --quiet --disable-pip-version-check fastapi==0.115.12 uvicorn==0.34.2
pip show fastapi uvicorn oxyde | grep -E '^(Name|Version):'
Output:
Name: fastapi
Version: 0.115.12
Name: uvicorn
Version: 0.34.2
Name: oxyde
Version: 0.9.0
In the output the installed versions appear: FastAPI 0.115.12, Uvicorn 0.34.2 and, for the tool, 0.9.0. If the numbers are these, the versions match the ones fixed in this tutorial.
Step 3.8: I write the API: list, detail and creation of articles
The file main.py contains the whole API, and FastAPI(lifespan=db.lifespan(**DATABASES)) connects Oxyde to the server’s life cycle: the database connections open when the server starts and close when it stops. Each function with a decorator, meaning the line that starts with @ above the function, such as @app.get or @app.post, is an endpoint. GET /posts returns a list, GET /posts/{post_id} returns a single article, and POST /posts creates a new one. The incoming data is described by the class PostCreate, a Pydantic model (a class that checks data), and before creating the article, exists() checks that the author exists. The functions return the models directly, and FastAPI turns them into JSON.
File main.py:
from fastapi import FastAPI, HTTPException
from oxyde import db
from pydantic import BaseModel
from models import Author, Post
from oxyde_config import DATABASES
app = FastAPI(title="Mini blog", lifespan=db.lifespan(**DATABASES))
class PostCreate(BaseModel):
title: str
content: str
author_id: int
published: bool = False
@app.get("/posts")
async def list_posts(limit: int = 10):
return await Post.objects.order_by("id").limit(limit).all()
@app.get("/posts/{post_id}")
async def get_post(post_id: int):
return await Post.objects.get(id=post_id)
@app.post("/posts", status_code=201)
async def create_post(data: PostCreate):
if not await Author.objects.filter(id=data.author_id).exists():
raise HTTPException(400, "Autore non trovato")
return await Post.objects.create(**data.model_dump())
python -c "import main; print(sorted(f'{m} {r.path}' for r in main.app.routes if r.path.startswith('/posts') for m in r.methods))"
Output:
['GET /posts', 'GET /posts/{post_id}', 'POST /posts']
The final command prints the registered endpoints: GET /posts, GET /posts/{post_id} and POST /posts. If you see all three, the file was read and the three functions are registered.
Step 3.9: I start the server in the background
uvicorn main:app starts the server: main is the file and app is the FastAPI object inside it. With --host 127.0.0.1 and --port 8000 the server listens only on your own computer, on port 8000, which is the number that identifies the service on that computer. A server does not end by itself, because it keeps waiting for requests: for this reason we start it in the background, meaning in parallel, and the tutorial continues after a few seconds. The server’s messages go into the file server.log, and the process number goes into the file server.pid, which we will need to stop it.
echo "$BASHPID" > server.pid
exec uvicorn main:app --host 127.0.0.1 --port 8000 > server.log 2>&1
Step 3.10: I try the API with curl: list, detail and an article that does not exist
curl sends HTTP requests from the command line: HTTP is the protocol that browsers and programs use to ask web servers for pages and data. The first loop waits for the server to respond, then we count in the log the lines “Application startup complete”: the number 1 confirms that the startup is complete. GET /posts?limit=2 returns the first two articles in JSON, and GET /posts/4 the details of one article. The JSON contains all the fields of the model: author is null because the author was not loaded with join(), as in part 2, while author_id contains its number. The -w option prints the HTTP status code after the response: 200 means everything went well.
for i in $(seq 1 40); do curl -s -o /dev/null http://127.0.0.1:8000/posts && break; sleep 0.25; done
grep -c "Application startup complete" server.log
echo "--- GET /posts?limit=2 ---"
curl -s -w "\nstato HTTP: %{http_code}\n" "http://127.0.0.1:8000/posts?limit=2"
echo "--- GET /posts/4 ---"
curl -s -w "\nstato HTTP: %{http_code}\n" http://127.0.0.1:8000/posts/4
echo "--- GET /posts/999 ---"
curl -s -w "\nstato HTTP: %{http_code}\n" http://127.0.0.1:8000/posts/999
echo "--- nel log del server ---"
for i in $(seq 1 20); do grep -q "exceptions.NotFoundError: " server.log && break; sleep 0.25; done
grep -m 1 -o "oxyde.exceptions.NotFoundError: .*" server.log || tail -n 5 server.log
Output:
1
--- GET /posts?limit=2 ---
[{"id":1,"title":"Primi passi con Oxyde","content":"Installazione e primo modello.","published":true,"views":120,"author":null,"author_id":1},{"id":2,"title":"Le migrazioni spiegate bene","content":"makemigrations e migrate.","published":true,"views":45,"author":null,"author_id":1}]
stato HTTP: 200
--- GET /posts/4 ---
{"id":4,"title":"Filtri e lookup in Oxyde","content":"filter, exclude e lookup.","published":true,"views":300,"author":null,"author_id":2}
stato HTTP: 200
--- GET /posts/999 ---
Internal Server Error
stato HTTP: 500
--- nel log del server ---
oxyde.exceptions.NotFoundError: Post matching query not found
In the output you see the number 1 for the startup, the two articles and the details of article 4, each with stato HTTP: 200. The request to /posts/999 instead returns the text Internal Server Error, in English, with status 500: in the server log, NotFoundError appears with the message Post matching query not found. A 500 error explains nothing to the person using the API, and we fix it in step 3.11.
Step 3.11: I turn the missing article into a 404 and stop the server
We fix the detail endpoint with the pattern that the documentation suggests for APIs: get() goes inside a try, and if NotFoundError arrives, we raise HTTPException(404, ...), which FastAPI turns into a response with code 404 and a message in JSON. We also add a very simple HTML page at the address /: the function home reads the latest 5 articles and puts them in a list, and escape() turns special characters in the titles, such as < and &, into safe text. A few lines of CSS, which are the rules that decide how the page looks, give it a tidy appearance, and response_class=HTMLResponse makes FastAPI send the text as a web page and not as JSON. The running server still uses the old version of the file, so we stop it with kill using the number in server.pid, and wait waits until it has really ended.
File main.py:
from html import escape
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse
from oxyde import NotFoundError, db
from pydantic import BaseModel
from models import Author, Post
from oxyde_config import DATABASES
app = FastAPI(title="Mini blog", lifespan=db.lifespan(**DATABASES))
class PostCreate(BaseModel):
title: str
content: str
author_id: int
published: bool = False
@app.get("/", response_class=HTMLResponse)
async def home():
posts = await Post.objects.order_by("-id").limit(5).all()
voci = "\n".join(f"<li>{escape(p.title)}</li>" for p in posts)
stile = (
"body{font-family:sans-serif;max-width:40rem;margin:2rem auto;padding:0 1rem;color:#222}"
"h1{border-bottom:3px solid #2b6cb0;padding-bottom:.4rem}"
"li{margin:.5rem 0;padding:.6rem .8rem;background:#edf2f7;border-radius:6px;list-style:none}"
)
return (
f"<!doctype html><html lang='it'><head><meta charset='utf-8'><title>Mini blog</title><style>{stile}</style></head>"
f"<body><h1>Mini blog</h1><h2>Ultimi articoli</h2><ul>\n{voci}\n</ul></body></html>"
)
@app.get("/posts")
async def list_posts(limit: int = 10):
return await Post.objects.order_by("id").limit(limit).all()
@app.get("/posts/{post_id}")
async def get_post(post_id: int):
try:
return await Post.objects.get(id=post_id)
except NotFoundError:
raise HTTPException(404, "Articolo non trovato")
@app.post("/posts", status_code=201)
async def create_post(data: PostCreate):
if not await Author.objects.filter(id=data.author_id).exists():
raise HTTPException(400, "Autore non trovato")
return await Post.objects.create(**data.model_dump())
kill "$(cat server.pid)"
wait "$(cat server.pid)" 2>/dev/null
curl -s -o /dev/null http://127.0.0.1:8000/posts || echo "server fermato"
Output:
server fermato
In the output only the line server fermato appears, which confirms that the process has ended. The updated main.py file is loaded in the next step, when we restart the server.
Step 3.12: I restart the server with the new version
We start the server again, the same way as in step 3.9: now it loads the corrected main.py file.
echo "$BASHPID" > server.pid
exec uvicorn main:app --host 127.0.0.1 --port 8000 > server.log 2>&1
Step 3.13: I try again: 404, creating an article and a nonexistent author
Now /posts/999 responds with 404 and the message Articolo non trovato. With curl -X POST and a JSON body we create an article: the server responds with 201 (created) and returns the article with the id assigned by the database. If the author given does not exist, the endpoint responds with 400 and a message that we wrote ourselves. Then we read the article we just created again with a GET request, and finally we ask for the HTML page at the address /: with grep we show only its title and the list.
for i in $(seq 1 40); do curl -s -o /dev/null http://127.0.0.1:8000/posts && break; sleep 0.25; done
echo "--- GET /posts/999 ---"
curl -s -w "\nstato HTTP: %{http_code}\n" http://127.0.0.1:8000/posts/999
echo "--- POST /posts ---"
curl -s -w "\nstato HTTP: %{http_code}\n" -X POST http://127.0.0.1:8000/posts \
-H "Content-Type: application/json" \
-d '{"title": "Scritto con l API", "content": "Creato con una richiesta POST.", "author_id": 3}'
echo "--- POST /posts con un autore che non esiste ---"
curl -s -w "\nstato HTTP: %{http_code}\n" -X POST http://127.0.0.1:8000/posts \
-H "Content-Type: application/json" \
-d '{"title": "Senza autore", "content": "Non verrà salvato.", "author_id": 99}'
echo "--- GET /posts/12 ---"
curl -s -w "\nstato HTTP: %{http_code}\n" http://127.0.0.1:8000/posts/12
echo "--- GET / (pagina HTML) ---"
curl -s http://127.0.0.1:8000/ | grep -E "<h1>|<li>"
Output:
--- GET /posts/999 ---
{"detail":"Articolo non trovato"}
stato HTTP: 404
--- POST /posts ---
{"id":12,"title":"Scritto con l API","content":"Creato con una richiesta POST.","published":false,"views":0,"author":null,"author_id":3}
stato HTTP: 201
--- POST /posts con un autore che non esiste ---
{"detail":"Autore non trovato"}
stato HTTP: 400
--- GET /posts/12 ---
{"id":12,"title":"Scritto con l API","content":"Creato con una richiesta POST.","published":false,"views":0,"author":null,"author_id":3}
stato HTTP: 200
--- GET / (pagina HTML) ---
<!doctype html><html lang='it'><head><meta charset='utf-8'><title>Mini blog</title><style>body{font-family:sans-serif;max-width:40rem;margin:2rem auto;padding:0 1rem;color:#222}h1{border-bottom:3px solid #2b6cb0;padding-bottom:.4rem}li{margin:.5rem 0;padding:.6rem .8rem;background:#edf2f7;border-radius:6px;list-style:none}</style></head><body><h1>Mini blog</h1><h2>Ultimi articoli</h2><ul>
<li>Scritto con l API</li>
<li>Finalmente online</li>
<li>Articolo confermato</li>
<li>Il mio primo articolo</li>
<li>Appunti su SQLite</li>
The status codes tell you how each request went: 404 for the article that does not exist, 201 for the one created (with id 12), 400 for the nonexistent author, and 200 for the re-read. The text you see for the page is HTML code, which the browser turns into a page; the first item in the list is Scritto con l API, that is, the article we just created.
Step 3.14: I look at the page in the browser
Now we look at the same page as a person would see it: it is what curl showed us as text, but with the look given by the CSS.
When you open http://127.0.0.1:8000/ in the browser, while the server is running, you will see the title “Mini blog” and the list of the latest five articles, with the one created with POST at the top.

Step 3.15: I stop the server and check the database
When the work is done, we stop the server with kill and wait, as in step 3.11: a server left on would keep occupying port 8000. Then we check directly in the database the effect of the requests: the article created with POST is there, the one with the nonexistent author is not. It is the same count check used for the transactions.
File finale.py:
import asyncio
from oxyde import db
from conteggi import conteggi
from models import Post
from oxyde_config import DATABASES
async def main():
async with db.connect(DATABASES["default"]):
print("nel database:", await conteggi())
ultimo = await Post.objects.order_by("-id").first()
print(f"ultimo articolo: {ultimo.id}: {ultimo.title} | autore {ultimo.author_id}")
if __name__ == "__main__":
asyncio.run(main())
kill "$(cat server.pid)"
wait "$(cat server.pid)" 2>/dev/null
curl -s -o /dev/null http://127.0.0.1:8000/posts || echo "server fermato"
python finale.py
Output:
server fermato
nel database: 6 autori, 12 articoli
ultimo articolo: 12: Scritto con l API | autore 3
The line server fermato confirms that it has closed. The database contains 6 authors and 12 articles: compared with step 3.6, where there were 6 authors and 11 articles, there is one more, the last one, created with POST, which is number 12, Scritto con l API, by author 3.
The most common mistake
The symptom: after an error, the database contains an author without their article, even though the two writes were inside transaction.atomic().
The cause: the exception was caught with try/except inside the atomic() block. This way the block ends normally, and the transaction confirms what had already been written: the rollback happens only if the exception leaves the block.
The fix: put the try/except outside transaction.atomic(), so the exception goes through the block and cancels everything. If you want to cancel only part of the work, use a nested atomic(), which is a savepoint, and catch the exception outside of it. The problem is shown in step 3.5 and the fix in step 3.6.
Summary
transaction.atomic()groups several writes: if the block ends well, they are all confirmed; if an exception leaves it, they are all cancelled.- An
atomic()inside another one creates a savepoint: an error there cancels only that part. - Catching the exception inside the
atomic()block prevents the rollback: thetry/exceptmust go outside. - All the tool’s exceptions come from
OxydeError; among the common ones areNotFoundError,MultipleObjectsReturnedandUniqueViolationError. - With FastAPI,
FastAPI(lifespan=db.lifespan(...))is enough to open and close the connections together with the server; the models are returned directly as JSON. - A
get()without error handling, for an article that does not exist, makes the server respond with a 500 error: it must be turned into a 404. - The tool is at version 0.x: fix the version and check the behavior with your own tests.
Things to keep in mind
- Version 0.x. This Python ORM is at version 0.x, and its interface may change between one minor version and the next. In practice, it is best to fix the version, as we did with
==, and check the behavior again before updating it. - Documentation not always accurate. Some behaviors do not match what the documentation says: in practice, an example copied from there should be checked with a test before you trust it.
- Crashes at shutdown. Some runs ended with
Aborted (core dumped)after printing the correct output. The cause has not been found and the data is limited, so, with what is known, it cannot be said when this happens. The numbers are in the verdict below. - Migrations and many-to-many relationships. Many-to-many relationships, meaning those where several rows of one table link to several rows of another, are still maturing. In practice, for migrations it is best to read the SQL with
oxyde sqlmigratebefore applying them.
The verdict on Oxyde
What works
- The Django-style query interface works as described:
filter,exclude, ordering, pages, lookups (comparisons on fields, such as__in),Qexpressions and groupings gave the expected results, checked with counts. - Migrations are generated and applied with two commands, and the SQL can be read before applying it with
oxyde sqlmigrate. - Transactions, rollbacks and savepoints behave as documented: the counts in the database confirm it.
- The exceptions have a clear hierarchy, with different classes for a row not found, multiple rows and a duplicate email.
- The integration with FastAPI takes only a few lines, and the models are returned directly as JSON.
- The
ON DELETE CASCADErule also works on SQLite (a database that lives in a single file): when you delete an author, their articles disappear too.
What is still young
- The tool is at version 0.x, and the documentation itself warns that the interface may change between one minor version and the next.
- The first version came out in December 2025: the project is about a year old.
- The documentation does not always match the real behavior: the address
sqlite:///blog.db, the name of the first migration,__containson SQLite andpost.authorwithoutjoin()behaved differently from what was written. - The project’s FAQ says that the basic operations are stable, but that migrations and many-to-many relationships are still maturing.
- In some runs, a program written with the tool printed all the correct output and then ended with the error
Aborted (core dumped), meaning it crashed at the moment of shutdown. This happened both to a Python script and to theoxyde migratecommand.
When to choose it
- For asynchronous projects (which wait for operations without blocking the program), for example with FastAPI, where you want Pydantic models and Django-style queries.
- For prototypes and projects where you can fix the exact version and check the behavior with your own tests.
When not to
- For synchronous code, meaning code that does not use Python’s asynchronous mode: this Python ORM is async from the ground up and does not offer a synchronous version.
- For projects that need a stable interface for years without having to follow updates.
- If you do not have the time to check the behavior: in this series, some pages of the documentation did not match version 0.9.0.
Glossary
- transaction: a group of database operations that are either all confirmed together or all cancelled together.
- rollback: cancellation of all the changes made inside a transaction that has not been confirmed.
- savepoint: a mark inside a transaction that you can go back to, cancelling only the work done after it.
- exception: an error signal that stops the program until someone handles it.
- endpoint: the address of an API that you send a request to in order to get a service.
- pip: a program that downloads and installs Python packages from the PyPI registry.
- server: a program that keeps listening and responds to the requests it receives.
- HTTP: the protocol that browsers and programs use to ask web servers for pages and data.
- JSON: a text format for exchanging structured data between different programs.
- status code: a three-digit number with which a server says how the request went.
- API: a set of rules with which one program asks something of another program or a service.
A note on the test
The steps were tested on Debian 12 with Python 3.11.2, in a clean Linux environment, with the fixed versions of Oxyde 0.9.0, FastAPI 0.115.12 and Uvicorn 0.34.2.