Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 77 ยท Python Interview Questions

Django and Flask: Request Cycle, ORM, Middleware and Hooks

Prepare Django and Flask interviews: the request cycle, middleware, the ORM and the N+1 problem, Flask hooks and contexts, and when to pick which framework.

"Django or Flask?" is almost guaranteed in a Python backend interview, and it is a trap if you answer with a slogan. The honest answer is about trade-offs: Django gives you an ORM, an admin, authentication, forms and migrations on day one; Flask gives you a small core and lets you choose the rest. The follow-up questions then test whether you understand what either framework does between receiving a request and sending a response.

Both frameworks really run in the site's Python runner (Pyodide), so every program below executes the actual library, installed on demand with micropip. The first run of a lesson page may take a few seconds while the packages download. There is no real web server: Django's Client and Flask's test_client() call the application directly, which is how most framework tests work anyway. The full lessons are in the Django and Flask tracks; for the language side of these answers see Python Decorators, Closures and Context Managers and Python Data Model Questions.

Django versus Flask

Django Batteries included, one way to do it.
Flask Small core, you pick the parts.

Both speak WSGI, and both support async in recent versions.

1 / 2

What happens to a request in Django?

Short answer: The web server hands the request to Django through WSGI (or ASGI for async). Django builds an HttpRequest, passes it inward through the middleware stack, resolves the URL to a view with the URL configuration, calls the view (which may use the ORM and a template), gets an HttpResponse, and passes it outward through the middleware in reverse order.

Django follows an MVT pattern (model, view, template). Django's view is what many frameworks call the controller; the template is the presentation layer. The framework itself plays the controller role by routing requests.

Middleware is a callable that wraps the rest of the stack. Code before get_response(request) runs on the way in; code after it runs on the way out. A middleware can short-circuit by returning its own response without calling the inner layers, which is how security checks, rate limits and CSRF rejection work. Order matters: the first entry in MIDDLEWARE is the outermost layer.

Python Django middleware order, with a short-circuit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read the three logs. A normal request passes in through timing then BlockAdmin, reaches the view, and comes out in reverse order. The /admin/ request is rejected by BlockAdmin, so the view never runs, but the outer timing layer still sees the 403 response and adds its header. For /missing/ the view raised Http404; Django's handler converted it to a 404 response before the middleware saw it, so the middleware's "out" code still ran.

How does the Django ORM work, and what is the N+1 problem?

Short answer: A model class maps to a table and instances map to rows. Book.objects.filter(...) builds a QuerySet, which is lazy: no SQL runs until you iterate it, slice it with a step, call list(), len(), bool(), or use .count(), .first() and similar. Once evaluated, a QuerySet caches its results, so iterating twice runs one query.

The N+1 problem appears when you load N objects and then touch a related object on each one. Accessing book.author runs a query per book unless you tell Django to fetch the relation up front:

  • select_related('author') uses a SQL JOIN and works for forward foreign keys and one-to-one relations.
  • prefetch_related('books') runs a second query and joins the results in Python; it is for reverse foreign keys and many-to-many relations.
  • annotate(n=Count('books')) pushes the counting into SQL when you only need a number.
Python N+1 queries and how to count them

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The counts are the answer interviewers want to hear: 13 queries for the naive loop (1 + 12 books), 1 with select_related; 5 for the reverse side (1 + 4 authors) against 2 with prefetch_related; and 1 with annotate. In real projects you find these with Django Debug Toolbar or by asserting query counts in tests (assertNumQueries).

Other ORM answers worth knowing:

  • Q and F objects: Q(a=1) | Q(b=2) builds OR conditions; F('stock') - 1 references a column inside the database, so an update such as Product.objects.update(stock=F('stock') - 1) avoids a race between reading and writing.
  • transaction.atomic() wraps several changes in one transaction that rolls back on an exception.
  • Migrations are generated from model changes (makemigrations) and applied with migrate; they are code that you commit.
  • get() versus filter(): get returns exactly one object or raises DoesNotExist or MultipleObjectsReturned; filter returns a QuerySet.
Python
# Read-only: typical Django model and view
class Order(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name="orders")
    total = models.DecimalField(max_digits=10, decimal_places=2)

def recent_orders(request):
    orders = Order.objects.select_related("customer").order_by("-id")[:20]
    return render(request, "orders.html", {"orders": orders})

What are Django's other built-in answers?

  • Authentication and sessions: django.contrib.auth provides users, password hashing (PBKDF2 by default, with salts and many iterations), permissions and sessions stored in the database by default.
  • CSRF protection: a CsrfViewMiddleware and the {% csrf_token %} tag protect state-changing requests from cross-site forgery (compare Security and Cryptography Questions).
  • Signals (post_save and friends) run code when something happens; they are convenient but make control flow hard to follow, so many teams prefer explicit calls.
  • Django REST Framework: serializers convert models to JSON and validate input; viewsets and routers generate the URL structure.
  • Class-based versus function-based views: function views are simple and explicit; class-based views and generic views reduce repeated code for CRUD.

How does Flask handle a request?

Short answer: A Flask app is a WSGI callable. For each request Flask creates a request context (the request object and the session) and an application context (current_app and the request-scoped storage g), runs the before_request hooks, dispatches to the view function chosen by the routing rules, runs after_request hooks on the response, and finally teardown_request hooks (which run even if an exception occurred). g is a per-request scratch space, good for a database connection or the current user. Errors are caught by @app.errorhandler.

Python Flask hooks and the request lifecycle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice in the third request how teardown_request receives the exception while after_request still runs on the 500 response Flask generated. The 404 handler is also shown: error handlers return the response to send.

Other Flask answers:

  • Blueprints group routes, templates and static files into reusable modules, and are registered on the app. Combined with an application factory (create_app(config)), they make a Flask project testable and configurable.
  • No ORM or forms built in: you add SQLAlchemy, Flask-Migrate, Flask-WTF or Flask-Login as needed.
  • Thread-safety: request and g look like globals but are context-local proxies, so each request sees its own data.
  • Production: never use app.run() with the debugger; run behind a WSGI server such as Gunicorn or uWSGI, usually behind nginx.
  • Async: both frameworks support async def views, but the ORM-heavy parts of Django and extensions in Flask may still be synchronous underneath.

So, Django or Flask?

Pick Django for content-heavy sites, admin-driven back offices, and teams that want conventions and a large ecosystem of reusable apps. Pick Flask (or FastAPI) for small services, APIs and teams that want to choose their own components. A good closing line: "The more of a standard web application I am building, the more I want Django's decisions made for me; the more unusual the service, the more I want Flask's freedom."

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In Django, in what order does the response pass through the middleware stack?

    The request goes inward through MIDDLEWARE in order; the response comes back outward in reverse order, like an onion.
  2. 2. A page loads 20 books and prints book.author.name for each. How many queries run without optimization, and what is the fix?

    One query loads the books, then one per book loads the author (N+1). select_related joins the author into the first query.
  3. 3. Which Django tool is for reverse foreign keys and many-to-many relations?

    prefetch_related runs a separate query and joins in Python, which suits reverse and many-to-many relations. select_related uses a JOIN for forward foreign keys and one-to-one.
  4. 4. Which Flask hook always runs, even if the view raised an exception?

    teardown_request functions run at the end of every request and receive the exception if one occurred.
  5. 5. What is Flask's g object?

    g is a namespace that lives for one application context (normally one request); it is a context-local proxy, not a shared global.

Summary

  • Django: WSGI/ASGI, then middleware inward, URL resolver, view, then middleware outward. A middleware can short-circuit and its order matters.
  • QuerySets are lazy and cached. Fix N+1 with select_related (forward FK, one-to-one) or prefetch_related (reverse and many-to-many); use annotate for aggregates and F for race-free updates.
  • Flask: request and app contexts, before_request, after_request, teardown_request, g, error handlers, blueprints and an application factory.
  • Django includes ORM, auth, admin, forms and migrations; Flask is a small core where you choose the parts.
  • Run both behind a production WSGI/ASGI server, never the development server.

Next: Java: OOP Core Questions, where the Python round gives way to the Java round.