Interview question
What are decorators in Python and how do you create custom decorators for Django views? Python में decorators क्या हैं और Django views के लिए custom decorators कैसे बनाते हैं?
Answer
Decorators are functions that modify or enhance other functions/classes without changing their source code. They wrap functions to add new functionality like authentication checks, logging, caching, or timing.
// Basic Python Decorator
def my_decorator(func):
def wrapper(*args, **kwargs):
print(f"Before calling {func.__name__}")
result = func(*args, **kwargs)
print(f"After calling {func.__name__}")
return result
return wrapper
@my_decorator
def greet(name):
print(f"Hello {name}")
greet("John") # Prints: Before, Hello John, After
// Django View Decorator - Authentication
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
@login_required(login_url="/login/")
def dashboard(request):
return HttpResponse("Welcome to dashboard")
# Redirects to /login/ if not authenticated
// Custom Decorator - Timing
import time
from functools import wraps
def timing_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} took {end-start:.2f} seconds")
return result
return wrapper
@timing_decorator
def slow_function():
time.sleep(2)
return "Done"
// Custom Decorator - Logging
from functools import wraps
import logging
logger = logging.getLogger(__name__)
def log_request(func):
@wraps(func)
def wrapper(request, *args, **kwargs):
logger.info(f"User {request.user} accessing {func.__name__}")
try:
response = func(request, *args, **kwargs)
logger.info(f"Response status: {response.status_code}")
return response
except Exception as e:
logger.error(f"Error in {func.__name__}: {str(e)}")
raise
return wrapper
@log_request
def view_books(request):
return JsonResponse({"books": [...]})
// Custom Decorator with Parameters
def rate_limit(calls_per_minute=60):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
# Implement rate limiting logic
return func(*args, **kwargs)
return wrapper
return decorator
@rate_limit(calls_per_minute=100)
def api_endpoint(request):
return JsonResponse({"data": []})
// Class-Based View Decorator
from django.utils.decorators import method_decorator
from django.views import View
@method_decorator(login_required, name="dispatch")
class BookListView(View):
def get(self, request):
return JsonResponse({"books": []})
// Multiple Decorators
from django.contrib.auth.decorators import login_required, permission_required
@login_required
@permission_required("myapp.can_edit_books")
def edit_book(request, book_id):
return JsonResponse({"status": "editing"})Decorators functions को wrap करके functionality add करते हैं। Python में बहुत common pattern है।
def my_decorator(func):
def wrapper(*args, **kwargs):
print(f"Before {func.__name__}")
result = func(*args, **kwargs)
print(f"After {func.__name__}")
return result
return wrapper
@my_decorator
def greet(name):
print(f"Hello {name}")
// Django में decorators
from django.contrib.auth.decorators import login_required
@login_required(login_url="/login/")
def dashboard(request):
return HttpResponse("Welcome")Was this answer clear?