python
46 lines · 1 tab
Priya Sharma
Jan 2026
1 tab
from django.db import transaction
from django.http import JsonResponse
@transaction.atomic
def transfer_funds(request):
"""Transfer money between accounts atomically."""
from_account_id = request.POST['from_account']
to_account_id = request.POST['to_account']
amount = Decimal(request.POST['amount'])
from_account = Account.objects.select_for_update().get(id=from_account_id)
to_account = Account.objects.select_for_update().get(id=to_account_id)
if from_account.balance < amount:
raise ValueError('Insufficient funds')
from_account.balance -= amount
to_account.balance += amount
from_account.save()
to_account.save()
# Create transaction record
Transaction.objects.create(
from_account=from_account,
to_account=to_account,
amount=amount
)
# If anything fails above, all changes roll back
return JsonResponse({'status': 'success'})
def create_order_with_items(order_data, items_data):
"""Create order and items in one transaction."""
with transaction.atomic():
order = Order.objects.create(**order_data)
for item_data in items_data:
OrderItem.objects.create(order=order, **item_data)
# Send email only if transaction succeeds
transaction.on_commit(lambda: send_order_email.delay(order.id))
return order
1 file · python
Explain with highlit
The atomic decorator/context manager ensures all-or-nothing database operations. I wrap related operations in @transaction.atomic or with transaction.atomic() blocks. If any operation fails, the entire transaction rolls back. This prevents partial data updates. I use savepoints for nested transactions. For long-running tasks, I keep transactions short to avoid lock contention. The on_commit hook runs code after successful commit. I'm careful with transactions in loops to prevent long-running locks. This is essential for maintaining data consistency.
Related snips
python
import os
import stat
for root, _dirs, files in os.walk('/etc'):
for name in files:
path = os.path.join(root, name)
Python security audit script for exposed risky filesystem state
python
auditing
host-security
by Kai Nakamura
1 tab
python
class Product(models.Model):
name = models.CharField(max_length=200)
slug = models.SlugField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
cost = models.DecimalField(max_digits=10, decimal_places=2)
margin = models.DecimalField(max_digits=5, decimal_places=2, blank=True)
Django model signals vs overriding save
django
python
models
by Priya Sharma
2 tabs
go
package dbutil
import (
"context"
"github.com/jackc/pgconn"
Retry Postgres serialization failures with bounded attempts
go
postgres
transactions
by Leah Thompson
1 tab
ruby
class SignupForm
include ActiveModel::Model
include ActiveModel::Attributes
attribute :account_name, :string
attribute :email, :string
Shallow Controller, Deep Params: Form Object Pattern
rails
activemodel
form-object
by codesnips
3 tabs
python
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
Django URL namespacing and reverse lookups
django
python
urls
by Priya Sharma
3 tabs
ruby
# Vulnerable: user input is concatenated directly into SQL.
email = params[:email]
password = params[:password]
sql = "SELECT * FROM users WHERE email = '#{email}' AND password_hash = '#{password}'"
user = ActiveRecord::Base.connection.execute(sql).first
SQL injection prevention with unsafe and safe query patterns
sql-injection
owasp
database
by Kai Nakamura
3 tabs
Share this code
Here's the card — post it anywhere.