### **Top 100 Flask Developer Interview Questions & Answers (Part 1)**
---
#### **1. What is Flask?**
**Answer:** Flask is a lightweight, micro web framework for Python. It provides essential tools to build web applications without enforced dependencies, emphasizing simplicity, flexibility, and modularity.
---
#### **2. How does Flask differ from Django?**
**Answer:** Flask is a **micro-framework** with minimal built-in features (e.g., no ORM or admin panel), offering flexibility. Django is a **full-stack framework** with "batteries-included" features (ORM, authentication, admin UI), prioritizing convention over configuration.
---
#### **3. Why use a virtual environment in Flask projects?**
**Answer:** Virtual environments isolate project dependencies (e.g., Flask, extensions) from the system-wide Python environment, avoiding conflicts and ensuring reproducibility.
---
#### **4. How do you create a basic Flask app?**
**Answer:**
```python
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, World!"
if __name__ == '__main__':
app.run(debug=True)
```
---
#### **5. What is the purpose of `if __name__ == '__main__'`?**
**Answer:** It ensures the Flask app runs **only when executed directly** (not imported as a module), preventing unintended execution during imports.
---
#### **6. How do you handle HTTP methods (GET/POST) in Flask?**
**Answer:** Use the `methods` parameter in route decorators:
```python
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
# Handle form submission
```
---
#### **7. What is Jinja2?**
**Answer:** Jinja2 is Flask’s **template engine** for rendering dynamic HTML. It supports variables, loops, conditionals, and template inheritance.
---
#### **8. How do you pass variables to a template?**
**Answer:** Use `render_template` with keyword arguments:
```python
return render_template('index.html', name='Alice')
```
---
#### **9. What is the difference between `render_template()` and `redirect()`?**
**Answer:**
- `render_template()`: Returns an **HTML response** (server-side rendering).
- `redirect()`: Sends an **HTTP 302 response** to redirect the client to another URL.
---
#### **10. How do you access form data in Flask?**
**Answer:** Use `request.form` for POST data:
```python
username = request.form['username']
```
---
#### **11. How do you define dynamic routes in Flask?**
**Answer:** Use `<variable>` in route paths:
```python
@app.route('/user/<username>')
def profile(username):
return f'Profile of {username}'
```
---
#### **12. How do you convert a URL variable to an integer?**
**Answer:** Use `<int:variable>`:
```python
@app.route('/post/<int:post_id>')
def show_post(post_id):
# post_id is an integer
```
---
#### **13. What is `url_for()` used for?**
**Answer:** It **generates URLs** for endpoints, avoiding hardcoded paths:
```python
url_for('login') # Returns '/login'
```
---
#### **14. How do you handle 404 errors in Flask?**
**Answer:** Use an error handler:
```python
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
```
---
#### **15. What are Flask Blueprints? Why use them?**
**Answer:** Blueprints modularize large applications into reusable components (e.g., `auth.py`, `blog.py`), improving organization and scalability.
---
#### **16. How do you structure a large Flask application?**
**Answer:** Use a **package-based structure**:
```
/myapp
/app
/blueprints
auth.py
blog.py
__init__.py
config.py
run.py
```
---
#### **17. What is the purpose of the `static` folder?**
**Answer:** It stores **static files** (CSS, JS, images), accessible via `/static/file.css`.
---
#### **18. How do you serve static files in Flask?**
**Answer:** Flask automatically serves files from the `static` folder. Use:
```html
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
```
---
#### **19. What is the difference between sessions and cookies in Flask?**
**Answer:**
- **Cookies**: Stored on the client-side (can be insecure).
- **Sessions**: Encrypted cookies managed by Flask (require `app.secret_key`).
---
#### **20. How do you set a secret key in Flask?**
**Answer:**
```python
app.secret_key = 'your_random_secret_key'
```
---
#### **21. How do you access query parameters (e.g., `?name=Alice`)?**
**Answer:** Use `request.args`:
```python
name = request.args.get('name')
```
---
#### **22. How do you handle file uploads in Flask?**
**Answer:**
```python
@app.route('/upload', methods=['POST'])
def upload():
file = request.files['file']
file.save('/path/to/save')
```
---
#### **23. What is `@app.before_request` used for?**
**Answer:** It runs a function **before every request** (e.g., checking user authentication).
---
#### **24. How do you get JSON data from a request?**
**Answer:** Use `request.get_json()`:
```python
data = request.get_json() # Returns a dict
```
---
#### **25. What is the difference between `request.json` and `request.data`?**
**Answer:**
- `request.json`: Parsed JSON data (dict).
- `request.data`: Raw request body (bytes).
---
#### **26. What is Flask-WTF?**
**Answer:** An extension for **form handling** with CSRF protection, validation, and integration with Jinja2.
---
#### **27. How do you validate forms in Flask?**
**Answer:** Use Flask-WTF validators:
```python
class LoginForm(FlaskForm):
email = StringField('Email', validators=[DataRequired(), Email()])
```
---
#### **28. How do you enable CSRF protection?**
**Answer:** Include `{{ form.csrf_token }}` in templates and initialize Flask-WTF with `app.secret_key`.
---
#### **29. How do you create a form using Flask-WTF?**
**Answer:**
```python
from flask_wtf import FlaskForm
class MyForm(FlaskForm):
name = StringField('Name')
```
---
#### **30. How do you display form errors in templates?**
**Answer:**
```jinja
{% for error in form.name.errors %}
<span>{{ error }}</span>
{% endfor %}
```
---
#### **31. What is SQLAlchemy?**
**Answer:** A Python **ORM** (Object-Relational Mapper) for interacting with databases using Python classes.
---
#### **32. How do you integrate SQLAlchemy with Flask?**
**Answer:** Use `Flask-SQLAlchemy`:
```python
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
```
---
#### **33. What is the difference between `db.session.add()` and `db.session.merge()`?**
**Answer:**
- `add()`: Inserts a **new record**.
- `merge()`: Updates an **existing record** (or inserts if not found).
---
#### **34. How do you define a model in Flask-SQLAlchemy?**
**Answer:**
```python
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
```
---
#### **35. How do you query data in Flask-SQLAlchemy?**
**Answer:**
```python
users = User.query.filter_by(name='Alice').all()
```
---
#### **36. What is Flask-Login?**
**Answer:** An extension for **user session management** (login, logout, session protection).
---
#### **37. How do you protect a route with Flask-Login?**
**Answer:** Use `@login_required`:
```python
from flask_login import login_required
@app.route('/profile')
@login_required
def profile():
...
```
---
#### **38. What is `UserMixin` in Flask-Login?**
**Answer:** A class providing default implementations for user methods (e.g., `is_authenticated`, `get_id`).
---
#### **39. How do you hash passwords in Flask?**
**Answer:** Use `werkzeug.security`:
```python
from werkzeug.security import generate_password_hash
hash = generate_password_hash('password')
```
---
#### **40. What is OAuth, and how is it implemented in Flask?**
**Answer:** OAuth allows **third-party authentication** (e.g., "Login with Google"). Use `Flask-OAuthlib` or `Authlib`.
---
#### **41. How do you test Flask applications?**
**Answer:** Use `pytest` with Flask’s `test_client`:
```python
def test_home(client):
response = client.get('/')
assert response.status_code == 200
```
---
#### **42. What is `app.test_client()`?**
**Answer:** A test client that simulates requests to the Flask app without running a server.
---
#### **43. How do you set up a test database?**
**Answer:** Use a separate config (e.g., `TestingConfig`) with an in-memory SQLite database.
---
#### **44. How do you mock external APIs in tests?**
**Answer:** Use `unittest.mock` or `pytest-mock` to patch HTTP requests.
---
#### **45. What is `app.test_request_context()`?**
**Answer:** Creates a temporary request context for testing functions that require `request` or `session`.
---
#### **46. How do you deploy Flask with Gunicorn?**
**Answer:**
```bash
gunicorn -w 4 app:app
```
(`-w 4` = 4 worker processes).
---
#### **47. What role does Nginx play in Flask deployment?**
**Answer:** Nginx acts as a **reverse proxy** to handle static files, SSL, and load balancing.
---
#### **48. How do you manage environment variables in Flask?**
**Answer:** Use `.env` files with `python-dotenv` or system environment variables.
---
#### **49. What is WSGI?**
**Answer:** **Web Server Gateway Interface** – a standard for Python web apps to communicate with servers (e.g., Gunicorn is a WSGI server).
---
#### **50. How do you enable HTTPS in Flask?**
**Answer:** Configure Nginx/Apache as a reverse proxy with SSL certificates (Flask itself doesn’t handle HTTPS).
---
#### **51. What is the application context in Flask?**
**Answer:** A context that provides access to `current_app` and `g`, active during request handling or CLI commands.
---
#### **52. What is the request context?**
**Answer:** A context that provides access to `request` and `session`, active during HTTP requests.
---
#### **53. How do you push an application context manually?**
**Answer:**
```python
with app.app_context():
# Access current_app or db here
```
---
#### **54. What is the difference between `current_app` and `app`?**
**Answer:**
- `current_app`: Proxy to the **active app instance** in the current context.
- `app`: The actual Flask application object.
---
#### **55. When is the application context pushed?**
**Answer:** Automatically during requests, CLI commands, or manually via `app.app_context()`.
---
#### **56. How do you prevent SQL injection in Flask?**
**Answer:** Use **parameterized queries** with SQLAlchemy (never concatenate user input into raw SQL).
---
#### **57. How do you prevent XSS attacks?**
**Answer:** Auto-escape variables in Jinja2 templates or use `Markup` for safe HTML.
---
#### **58. How do you secure cookies in Flask?**
**Answer:** Set `SESSION_COOKIE_SECURE=True` and `SESSION_COOKIE_HTTPONLY=True` in config.
---
#### **59. What is CSRF, and how do you mitigate it?**
**Answer:** **Cross-Site Request Forgery** – mitigated by using CSRF tokens (enabled by default in Flask-WTF).
---
#### **60. How do you validate user input in Flask?**
**Answer:** Use Flask-WTF validators or manual checks with `request.form`.
---
#### **61. How do you create a RESTful API with Flask?**
**Answer:** Use `Flask-RESTful` or return JSON responses with `jsonify()`.
---
#### **62. What is Flask-RESTful?**
**Answer:** An extension for building REST APIs with resource-based routing and request parsing.
---
#### **63. How do you return JSON responses?**
**Answer:** Use `jsonify()`:
```python
from flask import jsonify
return jsonify({'key': 'value'})
```
---
#### **64. How do you implement API versioning?**
**Answer:** Use URL prefixes (`/api/v1/resource`) or custom headers.
---
#### **65. What is the purpose of `jsonify()`?**
**Answer:** Converts a Python dict to a JSON response with the correct `Content-Type` header (`application/json`).
---
#### **66. How do you cache responses in Flask?**
**Answer:** Use `Flask-Caching` with backends like Redis or Memcached.
---
#### **67. What is memoization?**
**Answer:** Caching function results to avoid redundant computations (e.g., `@lru_cache`).
---
#### **68. How do you optimize database queries?**
**Answer:** Use eager loading (`db.joinedload`), avoid N+1 queries, and index columns.
---
#### **69. Do Blueprints affect performance?**
**Answer:** No – Blueprints are purely organizational and have negligible runtime overhead.
---
#### **70. How do you profile a Flask app?**
**Answer:** Use `flask-profiler` or Python’s `cProfile` module.
---
#### **71. What is Flask-Mail?**
**Answer:** An extension for sending emails via SMTP.
---
#### **72. How do you use Flask-Migrate?**
**Answer:** For **database migrations** using Alembic:
```bash
flask db init
flask db migrate
flask db upgrade
```
---
#### **73. What is Flask-Bootstrap?**
**Answer:** Integrates Bootstrap CSS/JS into Flask templates via Jinja2 macros.
---
#### **74. What is Flask-Script?**
**Answer:** Adds **command-line commands** (deprecated; use Flask’s built-in CLI instead).
---
#### **75. What is Flask-SocketIO?**
**Answer:** Adds **WebSocket support** for real-time communication (e.g., chat apps).
---
#### **76. How do you customize error pages?**
**Answer:** Register error handlers for codes like 404 or 500 (see Q14).
---
#### **77. What is the difference between 404 and 500 errors?**
**Answer:**
- **404**: Resource not found (client-side error).
- **500**: Internal server error (server-side bug).
---
#### **78. How do you log errors in Flask?**
**Answer:** Use `app.logger.error('Message')` or configure Python’s `logging` module.
---
#### **79. How do you handle exceptions globally?**
**Answer:**
```python
@app.errorhandler(Exception)
def handle_error(e):
return "An error occurred", 500
```
---
#### **80. What is `@app.teardown_request`?**
**Answer:** Runs after **every request** (even on exceptions) to clean up resources (e.g., closing DB connections).
---
#### **81. How do you manage configuration in Flask?**
**Answer:** Use `app.config.from_object()` with config classes (e.g., `DevelopmentConfig`).
---
#### **82. What is the `instance` folder?**
**Answer:** A directory for **sensitive config files** (e.g., `config.py`) not in version control.
---
#### **83. How do you switch between dev/prod configs?**
**Answer:** Set `FLASK_ENV=production` and load configs conditionally.
---
#### **84. What is `FLASK_ENV`?**
**Answer:** An environment variable to set the mode (`development` or `production`).
---
#### **85. How do you access config values?**
**Answer:**
```python
app.config['SECRET_KEY']
```
---
#### **86. How do you implement rate limiting?**
**Answer:** Use `Flask-Limiter`:
```python
limiter = Limiter(app, key_func=get_remote_address)
@limiter.limit("5/minute")
```
---
#### **87. What is a webhook?**
**Answer:** An HTTP callback triggered by external events (e.g., GitHub webhooks). Handle with POST routes.
---
#### **88. How do you use Celery with Flask?**
**Answer:** Configure Celery to use Flask’s app context for async tasks:
```python
celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])
```
---
#### **89. What is the `g` object?**
**Answer:** A **request-local** storage for data during a single request (e.g., `g.user = current_user`).
---
#### **90. How do you handle internationalization (i18n)?**
**Answer:** Use `Flask-Babel` for translations and locale management.
---
#### **91. What is Flask-Principal?**
**Answer:** Manages **user permissions** and role-based access control (RBAC).
---
#### **92. How do you implement WebSockets?**
**Answer:** Use `Flask-SocketIO` for bidirectional communication.
---
#### **93. How does Flask differ from FastAPI?**
**Answer:**
- **Flask**: Sync-focused, mature ecosystem.
- **FastAPI**: Async-native, auto-generated OpenAPI docs, Pydantic models.
---
#### **94. How do you stream large files?**
**Answer:** Use `Response` with a generator:
```python
def generate():
yield "data"
return Response(generate(), mimetype='text/csv')
```
---
#### **95. What is `@app.after_request`?**
**Answer:** Modifies responses **after** view execution (e.g., adding headers).
---
#### **96. How do you create a custom Flask extension?**
**Answer:** Follow the [Flask Extension Registry](https://flask.palletsprojects.com/en/latest/extensiondev/) guidelines.
---
#### **97. What is Flask-Admin?**
**Answer:** A admin interface generator for managing database models.
---
#### **98. How do you use JWT for authentication?**
**Answer:** Use `Flask-JWT-Extended` to issue/verify JSON Web Tokens.
---
#### **99. What is the difference between `session` and `g`?**
**Answer:**
- `session`: Persists **across requests** (client-side cookies).
- `g`: Persists **within a single request** (server-side).
---
#### **100. How do you secure a Flask API with tokens?**
**Answer:** Use JWT (via `Flask-JWT-Extended`) or OAuth2 (via `Authlib`).
---
Stay tuned for **Part 2 (Questions 101–200)**! 🚀