1. Django vs FastAPI: When to choose which?
Answer:
- Django: "Batteries-included". Best for full-stack apps, rapid prototyping, projects needing a built-in Admin, ORM, and Auth. Monolithic structure.
- FastAPI: Microservices, high-performance APIs, AsyncIO support, modern type hinting. Best for building APIs, ML model serving, and high-concurrency apps.
2. Explain the Django Request/Response Cycle.
Answer:
- Request comes to
wsgi.py/asgi.py. - Passed to
Middlewares(Security, Session, etc.). - URL Dispatcher (
urls.py) matches the route. - View (
views.py) processes logic (talks to Models/DB). - View returns a Response (HTML template or JSON).
3. How does FastAPI handle concurrency?
Answer: FastAPI is built on top of Starlette and Pydantic. It uses Python's async and await syntax to handle concurrency. It runs on an ASGI server (like Uvicorn), allowing it to handle many requests simultaneously without blocking I/O operations.
4. What is the N+1 problem in ORMs?
Answer: It happens when code executes N additional query statements to fetch the same data that could have been retrieved when executing the primary query.
Fix: Use select_related (JOIN) or prefetch_related (separate query + Python join) in Django.
5. What is WSGI vs ASGI?
Answer:
- WSGI (Web Server Gateway Interface): The synchronous standard for Python web applications (Django, Flask). It handles one request at a time per worker.
- ASGI (Asynchronous Server Gateway Interface): The spiritual successor to WSGI, designed for asynchronous applications (FastAPI, Django Channels). It supports WebSockets and long-polling.
6. Explain Django Middleware.
Answer: Middleware is a framework of hooks into Django's request/response processing. It's a light, low-level "plugin" system for globally altering Django's input or output.
Examples: AuthenticationMiddleware (associates users with requests), SessionMiddleware (manages sessions), GZipMiddleware (compresses content).
7. How does Dependency Injection work in FastAPI?
Answer: FastAPI has a powerful Dependency Injection system. You create a function (the dependency) and declare it in the path operation function's parameters using Depends().
FastAPI takes care of executing the dependency, handling sub-dependencies, and passing the result to your function. This is great for database sessions, authentication, and shared logic.
8. What are Django Signals?
Answer: Signals allow certain senders to notify a set of receivers that some action has taken place. They allow decoupled applications to get notified when events occur elsewhere in the framework.
Common Signals: pre_save, post_save, pre_delete, post_delete.
9. How do you secure a Python Web App?
Answer:
- SQL Injection: Use ORMs (Django ORM, SQLAlchemy) which parameterize queries by default.
- XSS (Cross-Site Scripting): Templates (Jinja2, DTL) auto-escape variables.
- CSRF (Cross-Site Request Forgery): Use CSRF tokens for state-changing requests (POST, PUT, DELETE).
- Dependencies: Regularly audit packages (`pip audit`).
10. What is Pydantic and why is it used in FastAPI?
Answer: Pydantic is a data validation and settings management library using Python type annotations. FastAPI uses it to:
- Validate request data (query params, body).
- Serialize response data (convert ORM objects to JSON).
- Generate OpenAPI (Swagger) schemas automatically.
11. How do you handle background tasks in Python web apps?
Answer: For long-running tasks (sending emails, processing images), you shouldn't block the request loop.
- Celery: The industry standard distributed task queue. Requires a broker like Redis or RabbitMQ.
- FastAPI BackgroundTasks: A simple, built-in way to run a function after returning a response. Good for small tasks.
- Redis Queue (RQ): A lighter alternative to Celery.
12. What is the Global Interpreter Lock (GIL)?
Answer: A mutex that allows only one thread to hold the control of the Python interpreter. This means even in a multi-threaded Python program, only one thread executes Python bytecode at a time.
Impact on Web: It limits CPU-bound performance. However, web apps are usually I/O-bound (waiting for DB/Network), so threading or async (which releases the GIL during I/O) still provides concurrency.