Atualize registros existentes com segurança
Altere campos e descarregue as mudanças corretamente.
Atualize registros existentes com segurança é uma aula grátis de Flask Academy no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Flask Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Flask Academy inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
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! 🎉
Perguntas Frequentes
A aula “Atualize registros existentes com segurança” é grátis?
Sim — o texto completo de “Atualize registros existentes com segurança” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Flask Academy, atualize para CoddyKit PRO. O curso de Flask Academy inclui 4 aulas no total.
O que vou aprender em “Atualize registros existentes com segurança”?
Altere campos e descarregue as mudanças corretamente. Você pratica Flask Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Flask Academy?
Nenhuma experiência prévia é necessária. Flask Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.
Quanto tempo leva a aula “Atualize registros existentes com segurança”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Flask Academy?
Sim. Cada aula de Flask Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Crie registros e confirme sessões
- Endpoints de leitura única e leitura múltipla
- Atualize registros existentes com segurança
- Exclua e trate linhas ausentes