Aggiornare in sicurezza i record esistenti
Modifichi i campi e invii correttamente le modifiche con flush.
Aggiornare in sicurezza i record esistenti è una lezione Flask Academy gratuita su CoddyKit. Questa è la lezione 3 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Flask Academy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Flask Academy include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
The U in CRUD
Updating means changing an existing row, not making a new one. The trick is to load the record first, then edit it. ✏️
Find Before You Change
Always fetch the target row by its id before touching it. get_or_404() loads it or stops with a clean 404.
user = User.query.get_or_404(user_id)Edit Like a Python Object
Once loaded, just reassign its attributes. SQLAlchemy notices the change and marks the object as dirty for you.
user.name = "New Name"Read the New Values
Updates usually carry the new data in the request body. Parse it with get_json() before applying anything.
data = request.get_json()Apply Fields Carefully
Only overwrite fields the client actually sent. Using get() with a fallback avoids wiping values to None by accident.
user.name = data.get("name", user.name)Commit the Change
No add() is needed for an existing row. A single commit() flushes your edits to the database.
db.session.commit()PUT Replaces, PATCH Tweaks
Use PUT when the client sends the whole object and PATCH when it sends only the fields it wants to change.
@app.route("/users/<int:id>", methods=["PATCH"])Validate Before Saving
Check incoming values before you commit. Reject bad data with a 400 so you never persist a broken record.
if not data.get("name"):
return jsonify(error="name required"), 400Roll Back if It Breaks
If the commit raises, call rollback() to discard the half-applied edit and leave the row exactly as it was.
except Exception:
db.session.rollback()Return the Updated Row
A good update reply sends back the fresh record with status 200, so the client sees the saved result.
return jsonify({"id": user.id, "name": user.name}), 200Load, Edit, Commit
The whole update flow is three beats: load the row, change its attributes, then commit. No new object ever appears.
Quick Check
You changed a loaded object's attribute. What must happen for the edit to stick?
Recap: Updating Records
You load with get_or_404, apply only sent fields, validate, then commit, rolling back on errors. Safe updates unlocked! 🎉
Domande Frequenti
La lezione «Aggiornare in sicurezza i record esistenti» è gratuita?
Sì — il testo completo di «Aggiornare in sicurezza i record esistenti» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Flask Academy, passa a CoddyKit PRO. Il corso Flask Academy include 4 lezioni in totale.
Cosa imparerò in «Aggiornare in sicurezza i record esistenti»?
Modifichi i campi e invii correttamente le modifiche con flush. Eserciti Flask Academy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare Flask Academy?
Non è richiesta alcuna esperienza precedente. Flask Academy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 3 di 4.
Quanto tempo richiede la lezione «Aggiornare in sicurezza i record esistenti»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione Flask Academy?
Sì. Ogni lezione Flask Academy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Creare record e fare il commit delle sessioni
- Endpoint per leggere uno o più elementi
- Aggiornare in sicurezza i record esistenti
- Eliminare e gestire le righe mancanti