Python Core Concepts and Django Framework Interview Topics

A concise self-introduction serves as a critical first impression. Interviewers assess five key dimensions through this interaction:

  • Consistency between spoken summary and written resume
  • Logical thinking, verbal articulation, and summarization ability
  • Conciseness, situational awareness, and presentation control
  • Professional self-awareness and motivation for career transition

Key principles: be succinct, highlight relevant achievements, guide questions toward your strengths. Use this structure:

Hello, I am [Name], graduated from [University]. Previously, I served as [Role] at [Company], focusing on [Domain]. I possess deep experience in [Core Skill]. I am eager to contribute to [Target Team/Project].

Django Core Knowledge

WSGI Protocol

The Python Web Server Gateway Interface defines how web servers (e.g., uWSGI, Gunicorn) communicate with Python web frameworks like Django or Flask—enabling standard request/response handling.

Django Request Lifecycle

  1. Client sends HTTP request
  2. WSGI wraps raw socket data into an environment dictionary
  3. Django constructs a WSGIHandler and invokes self.request_class(environ) to create the request object
  4. Middleware hooks: process_request, process_view, etc.
  5. URL routing → matches view function/class
  6. FBV: direct function execution; CBV: dispatch → method reflection
  7. Business logic using ORM, templates, external services
  8. Middleware response hooks: process_template_response, process_response
  9. Response sent back through WSGI to the client

Key Components & Patterns

  • Admin: Admin interface for CRUD on registered models
  • Model: DB abstraction layer (ORM)
  • Form: HTML generation + validation logic + error rednering
  • ModelForm: Combines model persistence with form semantics

Middleware Methods

Method Purpose
process_request Request interception (e.g., auth, IP rate-limiting)
process_view Access view metadata before execution
process_exception Global error handling
process_template_response Post-rendering response transformation
process_response Modify outgoing headers/content

FBV vs CBV

FBV uses standalone functions; CBV leverages classes for method segregation (get, post) and inheritance (e.g., mixins). Advantages include improved code reuse and cleaner separation of HTTP verb logic.

Adding Decorators to CBV

from django.utils.decorators import method_decorator

class MyView(View):
    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super().dispatch(*args, **kwargs)

# Or:
@method_decorator(login_required, name='dispatch')
class MyView(View): ...

Django ORM Highlights

  • .all(), .filter(), .exclude(), .order_by()
  • .get(): Exactly one match required;exceptions otherwise
  • .count(), .exists(), .first()

Optimizing Database Queries

  • select_related(): Uses SQL JOIN for foreign-key lookups (single query)
  • prefetch_related(): Executes separate queries per related table, then joins in Python (for reverse FK or M2M)

Cross-Site Request Forgery (CSRF) Flow

  1. Server generates unique token during initial response
  2. Token stored in session + embedded in cookie
  3. Client sends token in request header/body
  4. Server validates session token matches submitted token

Redis Caching in Django

CACHES = {
    'default': {
        'BACKEND': 'django_redis.cache.RedisCache',
        'LOCATION': 'redis://127.0.0.1:6379/0',
        'OPTIONS': {
            'CLIENT_CLASS': 'django_redis.client.DefaultClient',
            'CONNECTION_POOL_KWARGS': {'max_connections': 100}
        }
    }
}

DRF Key Components

Authentication, permissions, throttling, versioning, parsers, renderers, serializers, pagination, routing, viewsets.

DRF Authentication Pipeline

  1. APIView.dispatchinitialize_request
  2. self.initialperform_authentication
  3. self._authenticate() iterates through configured auth classes
  4. User object attached to request.user

Python Core Concepts

Handling Large Files within Limited Memory

from mmap import mmap

def line_generator(filepath):
    with open(filepath, "r+b") as f:
        mm = mmap(f.fileno(), 0)
        start = 0
        for idx, byte in enumerate(mm):
            if byte == ord('\n'):
                yield mm[start:idx+1].decode('utf-8', errors='ignore')
                start = idx + 1
        if start < len(mm):
            yield mm[start:].decode('utf-8', errors='ignore')

Recursive Directory Traversal

import os

def list_all_paths(root):
    for item in os.listdir(root):
        full_path = os.path.join(root, item)
        if os.path.isdir(full_path):
            yield from list_all_paths(full_path)
        else:
            yield full_path

Date Calculation

import datetime

def day_of_year(y, m, d):
    input_date = datetime.date(y, m, d)
    start_of_year = datetime.date(y, 1, 1)
    return (input_date - start_of_year).days + 1

Dictionary Sorting & Transformation

# Sort by value
d = {'a':24, 'g':52, 'i':12, 'k':33}
sorted_items = sorted(d.items(), key=lambda item: item[1])

# Parse key-value pairs
raw = "k:1|k1:2|k2:3|k3:4"
parsed = {k: int(v) for part in raw.split('|') for k, v in [part.split(':')]}

Memory Management & Optimizaton

Core mechanisms:

  • Reference counting: immediate object deallocation when count reaches zero
  • Cyclic garbage collector: detects and cleans unreachable cycles
  • Memory pools: optimized allocation for small objects (pymalloc)

Tuning tips:

  • Break circular references manually
  • Use gc.collect() for manual intervention
  • Increase thresholds: gc.set_threshold(700, 10, 10)

Decorators, Closures, Generators

Decorator (performance timing):

import time
from functools import wraps

def benchmark(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        t1 = time.perf_counter()
        result = func(*args, **kwargs)
        t2 = time.perf_counter()
        print(f"{func.__name__} executed in {t2 - t1:.4f}s")
        return result
    return wrapper

Closure definition: A nested function capturing variables from an enclosing scope.

Generator vs Iterator:
Generators automatically implement __iter__ and __next__ using yield. They retain state across calls and raise StopIteration upon exhaustion—ideal for memory-efficient streaming.

Object-Oriented & Design Patterns

Singleton Implementation

# Via class override
class Singleton:
    _instance = None
    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super().__new__(cls)
        return cls._instance

class Config(Singleton): pass
# Via metaclass
class SingletonMeta(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super().__call__(*args, **kwargs)
        return cls._instances[cls]

class Logger(metaclass=SingletonMeta): pass

Appropriate Use Cases for Singleton

  • Configuration managers
  • Connection pools (DB, Redis)
  • Logging infrastructure
  • Thread/resource pools

Lambda & Anonymous Functions

lambda defines inline, single-expression functions. Common idioms include:

  • Sorting keys: sorted(data, key=lambda x: x['score'])
  • Functional utilities: filter(lambda x: x > 0, nums), map(lambda x: x*2, nums)

Tags: python Django web-development ORM design-patterns

Posted on Sat, 13 Jun 2026 18:00:22 +0000 by surajkandukuri