python
36 lines · 1 tab
Priya Sharma
Jan 2026
1 tab
from django.db import transaction
from django.shortcuts import get_object_or_404
from django.http import JsonResponse
from .models import Product
@transaction.atomic
def purchase_product(request, product_id, quantity):
"""Purchase product with stock locking."""
# Lock the product row
product = Product.objects.select_for_update().get(id=product_id)
if product.stock < quantity:
return JsonResponse({'error': 'Insufficient stock'}, status=400)
# Decrement stock
product.stock -= quantity
product.save()
# Create order (simplified)
# Order.objects.create(...)
return JsonResponse({'success': True, 'remaining_stock': product.stock})
def try_reserve_product(product_id):
"""Try to reserve without waiting for lock."""
try:
with transaction.atomic():
product = Product.objects.select_for_update(nowait=True).get(id=product_id)
product.reserved = True
product.save()
return True
except models.DatabaseError:
# Lock not available
return False
1 file · python
Explain with highlit
select_for_update() locks rows until transaction completes, preventing race conditions. I use it for operations requiring read-modify-write atomicity like decrementing stock or updating counters. The lock is released on transaction commit/rollback. For non-blocking behavior, I use nowait=True or skip_locked=True. This is essential for concurrent writes to the same records. I wrap in transaction.atomic() for proper lock management. PostgreSQL and MySQL support this; SQLite has limited support. This prevents lost updates in high-concurrency scenarios.
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
rust
use crossbeam::channel::unbounded;
use std::thread;
fn main() {
let (tx, rx) = unbounded();
Crossbeam for advanced concurrent data structures
rust
concurrency
lock-free
by Marcus Chen
1 tab
javascript
// Creating a Promise
const myPromise = new Promise((resolve, reject) => {
const success = true;
setTimeout(() => {
if (success) {
Promises and async/await patterns for asynchronous JavaScript
javascript
promises
async-await
by Alex Chang
1 tab
rust
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
Channels (mpsc) for message passing between threads
rust
concurrency
channels
by Marcus Chen
1 tab
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
Share this code
Here's the card — post it anywhere.