### **Top 100 Flask Developer Interview Questions & Answers (Part 2: Questions 101–200)** --- #### **101. How do you implement asynchronous views in Flask?** **Answer:** Use `async def` with Flask 2.0+: ```python @app.route('/async') async def async_view(): await some_async_task() return "Done" ``` *Note:* Requires an ASGI server (e.g., Hypercorn) – **not** Gunicorn (WSGI). --- #### **102. What is the difference between WSGI and ASGI?** **Answer:** - **WSGI**: Synchronous protocol (Gunicorn). - **ASGI**: Supports async/await and WebSockets (Hypercorn, Daphne). --- #### **103. How do you run Flask with ASGI?** **Answer:** Use Hypercorn: ```bash hypercorn app:app --workers 4 ``` --- #### **104. Why avoid blocking calls in async views?** **Answer:** Blocking calls (e.g., `time.sleep()`) stall the event loop. Use `asyncio.to_thread()` for I/O-bound work: ```python await asyncio.to_thread(db.query, "SELECT * FROM users") ``` --- #### **105. How do you test async views?** **Answer:** Use `pytest-asyncio` with `test_client`: ```python async def test_async_view(client): response = await client.get('/async') assert response.status_code == 200 ``` --- #### **106. How do you prevent brute-force attacks on login?** **Answer:** 1. Use `Flask-Limiter` to rate-limit login attempts. 2. Implement account lockout after N failures. 3. Add CAPTCHA for repeated failures. --- #### **107. What is `secure_cookie` in Flask?** **Answer:** A secure way to store session data via **signed cookies** (uses `itsdangerous`). Never store sensitive data – sessions are client-side. --- #### **108. How do you rotate `SECRET_KEY` without breaking sessions?** **Answer:** Use `SECRET_KEY` rotation with `OLD_SECRET_KEYS`: ```python app.config.update( SECRET_KEY="new_key", OLD_SECRET_KEYS=["old_key1", "old_key2"] ) ``` *Flask-Session* handles this automatically. --- #### **109. What is the `SameSite` cookie attribute? Why use it?** **Answer:** Prevents CSRF by restricting cross-origin cookie sending: ```python app.config["SESSION_COOKIE_SAMESITE"] = "Lax" # or "Strict" ``` --- #### **110. Why is `app.run()` unsafe for production?** **Answer:** The built-in server is **single-threaded and unsecured**. Always use Gunicorn/Nginx in production. --- #### **111. How do you validate JWT tokens in Flask?** **Answer:** With `Flask-JWT-Extended`: ```python from flask_jwt_extended import jwt_required @app.route('/protected') @jwt_required() def protected(): return "Secret data" ``` --- #### **112. How do you set token expiration?** **Answer:** Configure in `config.py`: ```python JWT_ACCESS_TOKEN_EXPIRES = timedelta(hours=1) ``` --- #### **113. What is a "refresh token"? How is it implemented?** **Answer:** Long-lived token to obtain new access tokens. Use `create_refresh_token()`: ```python @jwt_refresh_token_required() def refresh(): identity = get_jwt_identity() return jsonify(access_token=create_access_token(identity)) ``` --- #### **114. How do you revoke JWT tokens?** **Answer:** Maintain a **token blocklist** (e.g., Redis) and check with `@jwt.token_in_blocklist_loader`. --- #### **115. How do you protect against timing attacks in password checks?** **Answer:** Use constant-time comparisons: ```python from werkzeug.security import safe_str_cmp if safe_str_cmp(user.password, input_password): # Valid ``` --- #### **116. How do you scale Flask horizontally?** **Answer:** 1. Stateless apps (store sessions in Redis). 2. Load balancer (Nginx) distributing traffic. 3. Shared database/cache (Redis, PostgreSQL). --- #### **117. Why use Redis for Flask sessions?** **Answer:** Centralized session storage enables **horizontal scaling** (multiple Gunicorn workers share sessions). --- #### **118. How do you configure Redis sessions?** **Answer:** With `Flask-Session`: ```python from flask_session import Session app.config["SESSION_TYPE"] = "redis" Session(app) ``` --- #### **119. What is the "thundering herd" problem? How to fix it?** **Answer:** Many clients simultaneously request expired resources (e.g., cache). Mitigate with: - Staggered cache expiration. - Background refresh (e.g., Celery task). --- #### **120. How do you implement circuit breakers in Flask?** **Answer:** Use `pybreaker` for external API calls: ```python breaker = CircuitBreaker(fail_max=5, reset_timeout=60) @breaker def call_external_api(): # ... ``` --- #### **121. What is `gunicorn --preload`? When to use it?** **Answer:** Loads the app **before** forking workers. Use for: - Large ML models (avoids per-worker duplication). - *Caution:* Increases memory usage. --- #### **122. How do you handle "too many open files" errors in Gunicorn?** **Answer:** Increase OS file descriptors: ```bash ulimit -n 4096 # Before starting Gunicorn ``` Or configure Gunicorn: ```python # gunicorn_config.py worker_connections = 1000 ``` --- #### **123. What is the purpose of `app.before_serving()`?** **Answer:** Runs **once** when the app starts (e.g., warm caches, connect to DB): ```python @app.before_serving def startup(): init_db() ``` --- #### **124. How do you gracefully restart Gunicorn?** **Answer:** Send `HUP` signal to reload workers without downtime: ```bash kill -HUP $(cat gunicorn.pid) ``` --- #### **125. Why avoid global variables in Flask?** **Answer:** They cause **race conditions** in multi-worker setups. Use `g` (request-local) or thread-safe storage (Redis). --- #### **126. How do you manage database connections per request?** **Answer:** Use `@app.teardown_request` to close connections: ```python @app.teardown_request def close_db(exception=None): db.session.remove() ``` --- #### **127. What is connection pooling? How is it configured in SQLAlchemy?** **Answer:** Reuses DB connections to avoid overhead. Configure via: ```python app.config["SQLALCHEMY_ENGINE_OPTIONS"] = { "pool_size": 10, "max_overflow": 20 } ``` --- #### **128. Why set `GUNICORN_CMD_ARGS="--preload"`?** **Answer:** Preloads the app into memory **before** forking workers (reduces memory usage for large apps). --- #### **129. How do you monitor Flask app performance?** **Answer:** Tools: - **Prometheus + Grafana** (metrics) - **Sentry** (error tracking) - **New Relic** (APM) --- #### **130. How do you log request/response details?** **Answer:** Custom middleware: ```python @app.before_request def log_request(): app.logger.info(f"Request: {request.method} {request.path}") ``` --- #### **131. How do you set up centralized logging with ELK Stack?** **Answer:** 1. Configure Python `logging` to output JSON. 2. Ship logs to Logstash via Filebeat. 3. Visualize in Kibana. --- #### **132. What is structured logging? Why use it?** **Answer:** Logs in machine-readable format (e.g., JSON). Enables: - Automated log analysis. - Easier filtering in tools like Datadog. --- #### **133. How do you handle timezone-aware datetimes in Flask?** **Answer:** Use `pytz` or `datetime.timezone`: ```python from datetime import datetime, timezone now = datetime.now(timezone.utc) ``` --- #### **134. How do you validate JSON schemas in requests?** **Answer:** Use `flask-jsonschema`: ```python from flask_jsonschema import JsonSchema jsonschema = JsonSchema(app) @jsonschema.validate('create_user') def create_user(): # Validated data in request.json ``` --- #### **135. How do you implement pagination?** **Answer:** With `SQLAlchemy` pagination: ```python page = request.args.get('page', 1, type=int) users = User.query.paginate(page=page, per_page=20) ``` --- #### **136. What is the N+1 query problem? How to fix it?** **Answer:** - **Problem**: 1 query + N child queries (e.g., `user.posts`). - **Fix**: Use `joinedload` (eager loading): ```python users = User.query.options(db.joinedload(User.posts)).all() ``` --- #### **137. How do you configure Python logging in Flask?** **Answer:** ```python import logging handler = logging.FileHandler('app.log') app.logger.addHandler(handler) app.logger.setLevel(logging.INFO) ``` --- #### **138. How do you log unhandled exceptions?** **Answer:** ```python @app.errorhandler(500) def log_error(e): app.logger.error(f"Server error: {e}") return "Internal error", 500 ``` --- #### **139. What is an "app factory"? Why use it?** **Answer:** Function that creates and configures the app: ```python def create_app(config): app = Flask(__name__) app.config.from_object(config) return app ``` *Benefits*: Testing (multiple instances), CLI flexibility. --- #### **140. How do you structure tests with app factories?** **Answer:** ```python # conftest.py @pytest.fixture def app(): return create_app(TestConfig) ``` --- #### **141. How do you mock database calls in tests?** **Answer:** Use `monkeypatch` with SQLAlchemy: ```python def test_user(monkeypatch): monkeypatch.setattr(User, 'query', Mock()) User.query.filter_by.return_value.first.return_value = User(name="Test") ``` --- #### **142. How do you test email sending?** **Answer:** Use `testing` mode in `Flask-Mail`: ```python app.config["TESTING"] = True with mail.record_messages() as outbox: send_email() assert len(outbox) == 1 ``` --- #### **143. How do you validate file uploads (e.g., image types)?** **Answer:** Check `mimetype`: ```python if file.mimetype not in ['image/jpeg', 'image/png']: return "Invalid file type", 400 ``` --- #### **144. How do you resize images on upload?** **Answer:** Use `Pillow`: ```python from PIL import Image img = Image.open(file) img.thumbnail((800, 800)) img.save('/path/to/resized.jpg') ``` --- #### **145. How do you deploy Flask with Docker?** **Answer:** `Dockerfile` example: ```dockerfile FROM python:3.9 COPY . /app WORKDIR /app RUN pip install gunicorn flask CMD ["gunicorn", "app:app", "-b", "0.0.0.0:5000"] ``` --- #### **146. Why use `.dockerignore`?** **Answer:** Prevents unnecessary files (e.g., `.git`, `venv`) from being copied into the image, reducing size. --- #### **147. How do you manage Docker environment variables?** **Answer:** Use `.env` file + `docker-compose.yml`: ```yaml services: web: env_file: .env ``` --- #### **148. How do you run database migrations in Docker?** **Answer:** Add a command to `docker-compose.yml`: ```yaml command: > sh -c "flask db upgrade && gunicorn app:app" ``` --- #### **149. What is a "health check" endpoint? How to implement?** **Answer:** Simple endpoint for load balancers: ```python @app.route('/health') def health(): return jsonify(status="ok", db_status=check_db()) ``` --- #### **150. How do you configure Nginx for Flask?** **Answer:** Basic `nginx.conf`: ```nginx server { location / { proxy_pass http://gunicorn:8000; proxy_set_header Host $host; } } ``` --- #### **151. How do you serve static files via Nginx (not Flask)?** **Answer:** ```nginx location /static { alias /app/static; } ``` --- #### **152. How do you enable HTTPS with Nginx?** **Answer:** Use Let's Encrypt: ```nginx server { listen 443 ssl; ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; } ``` --- #### **153. How do you handle WebSocket proxying in Nginx?** **Answer:** Add headers: ```nginx location /socket.io { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } ``` --- #### **154. What is `gunicorn --preload` vs `--preload-app`?** **Answer:** - `--preload`: Loads app **before** forking (shared memory). - `--preload-app`: *Deprecated* – same as `--preload`. --- #### **155. How do you limit Gunicorn worker memory?** **Answer:** Use `--max-requests` and `--max-requests-jitter`: ```bash gunicorn --max-requests 1000 --max-requests-jitter 50 app:app ``` *Restarts workers after ~1000 requests to prevent leaks.* --- #### **156. How do you debug memory leaks in Flask?** **Answer:** Tools: - `tracemalloc` (Python stdlib) - `gunicorn --preload` + `objgraph` - `Sentry` for production --- #### **157. How do you use Flask with GraphQL?** **Answer:** Use `graphene` + `flask-graphql`: ```python from flask_graphql import GraphQLView app.add_url_rule( '/graphql', view_func=GraphQLView.as_view('graphql', schema=schema) ) ``` --- #### **158. What is Flask-CORS? Why use it?** **Answer:** Handles **Cross-Origin Resource Sharing** headers. Critical for APIs consumed by frontend apps on different domains. --- #### **159. How do you configure CORS for specific origins?** **Answer:** ```python from flask_cors import CORS CORS(app, resources={r"/api/*": {"origins": "https://your-frontend.com"}}) ``` --- #### **160. How do you implement OAuth2 provider (not consumer) in Flask?** **Answer:** Use `Authlib`: ```python from authlib.integrations.flask_oauth2 import AuthorizationServer server = AuthorizationServer(app, query_client, save_token) ``` --- #### **161. How do you validate OAuth2 scopes?** **Answer:** With `Authlib`: ```python @app.route('/api/data') @require_oauth('profile') def profile(): # ... ``` --- #### **162. What is "token revocation"? How to implement?** **Answer:** Allowing users to invalidate tokens. Requires a token blocklist (see Q114). --- #### **163. How do you handle file streaming from S3?** **Answer:** Use `boto3` + `Response`: ```python from flask import Response def stream_from_s3(): obj = s3.get_object(Bucket='my-bucket', Key='file.zip') return Response( obj['Body'].iter_chunks(), mimetype='application/zip' ) ``` --- #### **164. How do you compress responses?** **Answer:** Use `Flask-Compress`: ```python from flask_compress import Compress Compress(app) ``` --- #### **165. How do you set response cache headers?** **Answer:** ```python @app.route('/data') @cache.cached(timeout=300) # Flask-Caching def data(): response = make_response(jsonify(...)) response.headers["Cache-Control"] = "public, max-age=300" return response ``` --- #### **166. What is "cache busting"? How to implement?** **Answer:** Force browser to fetch new assets. Append version hash to filenames: ```jinja <link rel="stylesheet" href="{{ url_for('static', filename='main.css', v='1.2.3') }}"> ``` --- #### **167. How do you handle background tasks without Celery?** **Answer:** Use `threading`: ```python from threading import Thread def send_async_email(app, msg): with app.app_context(): mail.send(msg) Thread(target=send_async_email, args=(app, msg)).start() ``` *Caution:* Not for CPU-heavy tasks. --- #### **168. How do you validate webhook signatures (e.g., Stripe)?** **Answer:** Verify payload with secret key: ```python signature = request.headers['Stripe-Signature'] if not hmac.compare_digest( signature, hmac.new(SECRET_KEY, request.data, 'sha256').hexdigest() ): abort(400) ``` --- #### **169. How do you implement SSO (Single Sign-On) in Flask?** **Answer:** Use `flask-oidc` for OpenID Connect or `python-social-auth` for OAuth2 providers. --- #### **170. What is Flask-DebugToolbar?** **Answer:** Development toolbar showing SQL queries, request variables, and performance stats. --- #### **171. How do you profile slow endpoints?** **Answer:** Use `flask-profiler`: ```python app.config["FLASK_PROFILER"] = { "enabled": True, "storage": {"engine": "sqlite"} } ``` --- #### **172. How do you enforce HTTPS in Flask?** **Answer:** Use `Talisman`: ```python from flask_talisman import Talisman Talisman(app, content_security_policy=default_content_policy) ``` --- #### **173. What is a "clickjacking" attack? How to prevent?** **Answer:** Embedding your site in an iframe. Mitigate with: ```python app.config["SESSION_COOKIE_SAMESITE"] = "Strict" app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(minutes=5) ``` --- #### **174. How do you set Content Security Policy (CSP) headers?** **Answer:** With `Talisman`: ```python csp = { 'default-src': "'self'", 'script-src': ["'self'", "trusted.cdn.com"] } Talisman(app, content_security_policy=csp) ``` --- #### **175. How do you handle Unicode errors in Flask?** **Answer:** Configure charset: ```python app.config["JSON_AS_ASCII"] = False # For JSON responses app.config["JSONIFY_MIMETYPE"] = "application/json; charset=utf-8" ``` --- #### **176. How do you internationalize error messages?** **Answer:** Use `Flask-Babel` with gettext: ```python from flask_babel import gettext @app.errorhandler(404) def not_found(e): return gettext("Page not found"), 404 ``` --- #### **177. How do you implement multi-tenancy?** **Answer:** Options: 1. **Database per tenant**: Use dynamic SQLAlchemy binds. 2. **Shared schema**: Add `tenant_id` to all tables. --- #### **178. How do you dynamically load blueprints?** **Answer:** Scan a directory: ```python for module in os.listdir("blueprints"): if module.endswith(".py"): bp = import_module(f"blueprints.{module[:-3]}").bp app.register_blueprint(bp) ``` --- #### **179. What is Flask-Principal? How does it work?** **Answer:** Manages user **permissions** via "needs" and "identity": ```python from flask_principal import Permission, RoleNeed admin_permission = Permission(RoleNeed('admin')) @admin_permission.require(http_exception=403) def admin_dashboard(): # ... ``` --- #### **180. How do you invalidate user sessions globally?** **Answer:** Bump a **session salt** in the database and check on login: ```python if user.session_salt != session.get('salt'): logout_user() ``` --- #### **181. How do you handle database schema migrations?** **Answer:** Use `Flask-Migrate` (Alembic): ```bash flask db migrate -m "Add email column" flask db upgrade ``` --- #### **182. How do you seed a database?** **Answer:** Create a CLI command: ```python @app.cli.command("seed-db") def seed_db(): db.session.add(User(name="Admin")) db.session.commit() ``` --- #### **183. How do you test database transactions?** **Answer:** Use `pytest-flask-sqlalchemy` to roll back after tests: ```python def test_user_creation(db_session): user = User(name="Test") db_session.add(user) db_session.commit() assert User.query.count() == 1 ``` --- #### **184. How do you implement soft deletes?** **Answer:** Add `is_deleted` column and override `query`: ```python class Base(db.Model): __abstract__ = True is_deleted = db.Column(db.Boolean, default=False) @classmethod def query(cls): return super().query.filter_by(is_deleted=False) ``` --- #### **185. How do you optimize full-text search?** **Answer:** Use database-native search (e.g., PostgreSQL `tsvector`) or `Elasticsearch`. --- #### **186. How do you handle database deadlocks?** **Answer:** 1. Retry transactions (with exponential backoff). 2. Use `SELECT ... FOR UPDATE` sparingly. 3. Keep transactions short. --- #### **187. What is "connection leaking"? How to prevent?** **Answer:** Connections not returned to the pool. Fix with: - `@app.teardown_request` (see Q126). - Context managers: ```python with db.session() as session: session.query(...) ``` --- #### **188. How do you monitor database queries in production?** **Answer:** - Log slow queries (`SQLALCHEMY_RECORD_QUERIES=True`). - Use `pg_stat_statements` (PostgreSQL). - APM tools (Datadog, New Relic). --- #### **189. How do you implement row-level security?** **Answer:** In PostgreSQL: ```sql CREATE POLICY user_policy ON users USING (id = current_user_id()); ``` Or in SQLAlchemy: `@event.listens_for(Query, 'before_compile')`. --- #### **190. How do you serve large CSV files efficiently?** **Answer:** Stream with `Response`: ```python def generate_csv(): yield "id,name\n" for user in User.query.yield_per(1000): yield f"{user.id},{user.name}\n" return Response(generate_csv(), mimetype='text/csv') ``` --- #### **191. How do you handle timezone conversions in templates?** **Answer:** Use `Flask-Babel`: ```jinja {{ datetime|format_datetime('short') }} ``` --- #### **192. How do you minify HTML/CSS/JS in Flask?** **Answer:** Use `Flask-Assets` with `cssmin`/`jsmin`: ```python assets = Environment(app) css = Bundle('src/*.css', filters='cssmin', output='gen/packed.css') assets.register('css_all', css) ``` --- #### **193. How do you implement "remember me" login?** **Answer:** With `Flask-Login`: ```python login_user(user, remember=True) app.config["REMEMBER_COOKIE_DURATION"] = timedelta(days=30) ``` --- #### **194. How do you invalidate "remember me" tokens?** **Answer:** Store token hashes in the DB and check on login. --- #### **195. What is Flask-Security?** **Answer:** All-in-one auth/security (login, registration, roles, 2FA). Built on Flask-Login and Flask-Principal. --- #### **196. How do you add 2FA (Two-Factor Auth)?** **Answer:** Use `Flask-Security` or `pyotp`: ```python import pyotp secret = pyotp.random_base32() totp = pyotp.TOTP(secret) if totp.verify(user_input): # Valid ``` --- #### **197. How do you handle GDPR data exports?** **Answer:** Create an endpoint that: 1. Anonymizes PII. 2. Returns user data as JSON/CSV. 3. Runs async (Celery) for large datasets. --- #### **198. How do you implement passwordless login?** **Answer:** 1. User enters email → send magic link. 2. Link contains JWT (expires in 5 mins). 3. Validate token on click. --- #### **199. How do you audit user actions?** **Answer:** Log critical actions to a separate table: ```python class AuditLog(db.Model): user_id = db.Column(db.Integer, db.ForeignKey('user.id')) action = db.Column(db.String(50)) timestamp = db.Column(db.DateTime, default=datetime.utcnow) ``` --- #### **200. How do you gracefully shut down workers during deploys?** **Answer:** In Gunicorn: ```bash gunicorn --graceful-timeout 30 --timeout 120 app:app ``` *Graceful timeout* allows in-flight requests to complete. --- **Part 3 (Questions 201–300) coming next!** 🔥