Flask Interview Questions and Answers


1. What is Flask?
  • Flask is a micro-framework for building web applications in Python. It's called a "micro-framework" because it provides a minimal core with basic features and relies on extensions for additional functionality like database integration, form handling, etc.
2. Why is Flask considered a "micro-framework"?
  • It's considered micro because it doesn't include built-in features for things like database abstraction, form validation, or authentication. It provides the core necessities (routing, request/response handling, templating) and allows developers to choose and integrate extensions for other needs.
3. What are the key components that Flask uses?
  • Werkzeug: A WSGI (Web Server Gateway Interface) utility library that handles requests and responses.
  • Jinja2: A modern and designer-friendly templating language for Python.
4. What are the advantages of using Flask?
  • Lightweight and minimal core.
  • Flexible and allows developers to choose their own libraries and tools.
  • Easy to learn and get started with.
  • Large ecosystem of extensions.
  • Good for building smaller applications, APIs, or microservices.
5. What are some potential disadvantages of using Flask?
  • Requires more manual setup and integration of extensions compared to a full-stack framework like Django.
  • Can be less opinionated, which might lead to more design decisions for developers.
6. Explain the concept of a Virtual Environment in Python and why it's important for Flask development.
  • A virtual environment is an isolated Python environment where you can install dependencies for a specific project without interfering with other projects or the global Python installation. It's crucial for Flask because it ensures that your project's dependencies are managed separately, avoiding version conflicts.
7. How do you install Flask?
  • Using pip: pip install Flask (preferably within a virtual environment).
8. How do you create a basic "Hello, World!" Flask application?
  • from flask import Flask
    
    app = Flask(__name__)
    
    @app.route('/')
    def hello_world():
        return 'Hello, World!'
    
    if __name__ == '__main__':
        app.run()
    
9. What does Flask(__name__) do?
  • It creates an instance of the Flask application. __name__ is a special Python variable that represents the name of the current module. Flask uses this to determine the root path for finding resources like templates and static files.
10. What is the purpose of the @app.route('/') decorator?
  • The @app.route('/') decorator is used to associate a URL path (in this case, the root path '/') with the following Python function (the view function). When a request comes in for that path, the decorated function is executed.
11. What is a view function in Flask?
  • A view function is a Python function that is mapped to a specific URL route using the @app.route() decorator. It's responsible for handling the request and returning a response.
12. How do you run a Flask application?
  • If your application file is named app.py, you can run it using the command line: flask run.
  • Alternatively, if you have the if __name__ == '__main__': app.run() block, you can run the file directly: python your_app_file.py.
13. What is the default host and port that the Flask development server runs on?
  • By default, it runs on 127.0.0.1 (localhost) and port 5000.
14. How do you change the host and port for the development server?
  • You can pass host and port arguments to the app.run() method (e.g., app.run(host='0.0.0.0', port=8000)).
15. What is debug mode in Flask? How do you enable it?
  • Debug mode provides helpful debugging information in the browser, including interactive debuggers, when errors occur. It should *never* be used in a production environment. You can enable it by setting debug=True in app.run() or by setting the FLASK_ENV environment variable to development.
16. How do you define dynamic URLs in Flask?
  • You use angle brackets in the route path (e.g., @app.route('/users/')). The dynamic segment is passed as an argument to the view function.
17. How do you specify variable types in dynamic URLs?
  • You can specify the type using a colon (e.g., @app.route('/posts/')). Common types include string, int, float, path, uuid.
18. How do you handle different HTTP methods (GET, POST, etc.) for a single route?
  • You specify the methods argument in the @app.route() decorator (e.g., @app.route('/submit', methods=['GET', 'POST'])). Inside the view function, you can check request.method.
19. How do you access data from a GET request's query string?
  • Using request.args, which is a dictionary-like object. You can access values using request.args.get('param_name') to avoid errors if the parameter is not present.
20. How do you access data from a POST request's form data?
  • Using request.form, which is a dictionary-like object. You access values using request.form.get('field_name').
21. How do you access JSON data in a request?
  • Using request.json, which parses the incoming JSON data into a Python dictionary or list.
22. How do you return a JSON response from a view function?
  • Using the jsonify() function from Flask (e.g., from flask import jsonify, then return jsonify({'message': 'Success'})).
23. How do you redirect a user to another URL?
  • Using the redirect() function from Flask (e.g., from flask import redirect, url_for, then return redirect(url_for('index'))).
24. What is the purpose of the url_for() function?
  • url_for() is used to dynamically build URLs for specific view functions. It takes the endpoint name (the function name by default) and any dynamic parameters as arguments. Using url_for() is preferred over hardcoding URLs, as it makes your application more flexible and maintainable.
25. How do you render an HTML template in Flask?
  • Using the render_template() function from Flask (e.g., from flask import render_template, then return render_template('index.html', data=my_data)).
26. Where should you store your HTML templates in a Flask project?
  • By default, Flask looks for templates in a folder named templates in the same directory as your application file or blueprint.
27. How do you pass variables from a view function to a Jinja2 template?
  • You pass them as keyword arguments to the render_template() function (e.g., render_template('index.html', user=current_user, posts=all_posts)). These variables are then accessible in the template.
28. How do you display a variable in a Jinja2 template?
  • Using double curly braces: {{ variable_name }}.
29. How do you use control structures (if statements, loops) in Jinja2 templates?
  • Using curly braces with percent signs:
    • If: {% if condition %} ... {% endif %}
    • For: {% for item in collection %} ... {% endfor %}
30. What is template inheritance in Jinja2? Why is it useful?
  • Template inheritance allows you to create a base template with common structure (like headers, footers, navigation) and then extend it in other templates. This promotes code reuse and makes it easier to maintain a consistent look and feel across your site.
31. How do you define blocks and extend templates in Jinja2?
  • In the base template, you define blocks using {% block block_name %} ... {% endblock %}.
  • In child templates, you extend the base template using {% extends 'base.html' %} and then override or add to blocks using {% block block_name %} ... {% endblock %}.
32. Where should you store static files (CSS, JS, images) in a Flask project?
  • By default, Flask looks for static files in a folder named static in the same directory as your application file or blueprint.
33. How do you link to static files in a Jinja2 template?
  • Using the url_for() function with the 'static' endpoint and the filename: {{ url_for('static', filename='css/style.css') }}.
34. What is the purpose of Flask-WTF?
  • Flask-WTF is an extension that integrates Flask with WTForms, a flexible library for handling web forms, including form definition, validation, and rendering.
35. How do you define a form using Flask-WTF?
  • You create a Python class that inherits from FlaskForm and define form fields and validators as class attributes.
36. How do you render a form in a Jinja2 template using Flask-WTF?
  • You pass the form object to the template and then use Jinja2 syntax to render individual fields or the entire form.
37. How do you validate a form submission using Flask-WTF?
  • In your view function, you instantiate the form with request.form (or other request data) and then call form.validate_on_submit() within a conditional statement (typically if form.validate_on_submit():).
38. What is CSRF protection? How does Flask-WTF help with it?
  • CSRF (Cross-Site Request Forgery) is an attack where malicious code tricks a user's browser into performing unwanted actions on a website where they are authenticated. Flask-WTF provides built-in CSRF protection by generating and validating CSRF tokens in forms.
39. What is Flask-SQLAlchemy?
  • Flask-SQLAlchemy is an extension that provides seamless integration between Flask and SQLAlchemy, a powerful and flexible SQL ORM.
40. How do you configure Flask-SQLAlchemy?
  • You set the SQLALCHEMY_DATABASE_URI configuration variable in your Flask app (e.g., app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db').
  • You create a SQLAlchemy instance: db = SQLAlchemy(app).
41. How do you define a database model using Flask-SQLAlchemy?
  • You create a Python class that inherits from db.Model and define database columns using db.Column().
42. How do you create the database tables based on your models?
  • Using db.create_all() (usually run within a Flask application context).
43. What is Flask-Migrate? Why is it used?
  • Flask-Migrate is an extension that integrates Flask-SQLAlchemy with Alembic, a database migration tool. It's used to manage changes to your database schema over time as your models evolve, without losing existing data.
44. How do you perform basic CRUD (Create, Read, Update, Delete) operations with Flask-SQLAlchemy?
  • Create: Create an instance of your model, add it to the session (db.session.add(instance)), and commit (db.session.commit()).
  • Read: Use query methods on your model (e.g., Model.query.all(), Model.query.get(id), Model.query.filter_by(...)).
  • Update: Retrieve the record, modify its attributes, and commit the session (db.session.commit()).
  • Delete: Retrieve the record, delete it from the session (db.session.delete(record)), and commit (db.session.commit()).
45. What is Flask-Login?
  • Flask-Login is an extension that provides user session management for Flask, handling common tasks like logging users in and out, and remembering logged-in users.
46. How do you integrate Flask-Login with your user model?
  • Your user model class needs to inherit from UserMixin (or implement the required properties and methods).
  • You need to provide a user loader function that Flask-Login uses to load a user from their ID stored in the session.
47. How do you protect routes that require a user to be logged in?
  • Using the @login_required decorator from Flask-Login on the view function.
48. How do you log a user in and out using Flask-Login?
  • Use login_user(user_object) to log in.
  • Use logout_user() to log out.
49. What is the difference between Authentication and Authorization?
  • Authentication: Verifying the identity of a user (e.g., logging in with username and password).
  • Authorization: Determining what an authenticated user is allowed to do (e.g., checking if a user has admin privileges).
50. What are Blueprints in Flask? Why are they useful?
  • Blueprints are a way to organize your Flask application into smaller, reusable components. They define collections of routes, templates, and static files that can be registered with a Flask application. They are useful for structuring larger applications and creating reusable app components.
51. How do you create and register a Blueprint?
  • Create a Blueprint instance: my_blueprint = Blueprint('my_blueprint', __name__).
  • Define routes using the Blueprint instance: @my_blueprint.route('/my-route').
  • Register the Blueprint with the app: app.register_blueprint(my_blueprint, url_prefix='/prefix').
52. Explain the difference between the Application Context and the Request Context in Flask.
  • Application Context: Exists for the lifetime of the application. It makes the application instance (current_app) available.
  • Request Context: Exists for the duration of a single request. It makes the request (request), session (session), and the g object available.
53. What is the purpose of the g object in Flask?
  • The g object is a global object within the application context that can be used to store data that is specific to the current request. It's a good place to store resources like database connections or the currently logged-in user.
54. How do you handle file uploads in Flask?
  • Access uploaded files using request.files.
  • Save the uploaded file to a destination.
  • Use libraries like Werkzeug's secure_filename() to sanitize filenames.
55. How do you configure Flask applications?
  • Using the app.config dictionary. You can set configuration variables directly (e.g., app.config['SECRET_KEY'] = 'your_secret') or load them from a configuration file.
56. What is the purpose of the SECRET_KEY configuration variable?
  • The SECRET_KEY is used for cryptographic operations, such as signing session cookies and CSRF tokens. It should be a long, random, and unique string and kept secret.
57. How do you handle sessions in Flask?
  • Flask provides a simple session object (session) that stores data on the server-side (by default, encrypted and signed cookies). You can treat it like a dictionary (e.g., session['username'] = user.username). Requires a SECRET_KEY.
58. What are Flask Extensions? How do you use them?
  • Flask Extensions are Python packages that integrate with Flask to provide additional functionality. You install them using pip and typically initialize them with your Flask application instance.
59. Name some popular Flask Extensions.
  • Flask-SQLAlchemy (Database ORM)
  • Flask-WTF (Form Handling)
  • Flask-Login (User Session Management)
  • Flask-Migrate (Database Migrations)
  • Flask-RESTful / Flask-RESTX (Building REST APIs)
  • Flask-Mail (Sending Emails)
  • Flask-Caching (Caching)
60. How do you handle errors and exceptions in Flask?
  • Using the @app.errorhandler() decorator to register error handler functions for specific HTTP status codes or exception types.
61. What is the difference between app.run() and using a production WSGI server?
  • app.run() is Flask's built-in development server. It's not suitable for production because it's not designed for high traffic, security, or reliability.
  • Production WSGI servers (like Gunicorn or uWSGI) are optimized for serving web applications in production environments.
62. What is WSGI (Web Server Gateway Interface)?
  • WSGI is a standard Python interface that defines how web servers communicate with web applications written in Python. Flask applications are WSGI-compliant.
63. Name some common WSGI servers.
  • Gunicorn
  • uWSGI
  • Waitress
64. What is a reverse proxy? Why is it often used with Flask in production?
  • A reverse proxy (like Nginx or Apache) sits in front of the WSGI server. It handles incoming requests, serves static files efficiently, manages SSL/TLS, and can load balance requests across multiple instances of your application.
65. How do you serve static files efficiently in production?
  • By configuring a reverse proxy (like Nginx or Apache) to serve static files directly, bypassing the Python application and WSGI server.
66. How do you handle environment-specific configurations in Flask?
  • Using environment variables (e.g., os.environ).
  • Loading configuration from different files based on the environment (e.g., config.py, config_prod.py).
  • Using Flask-specific configuration patterns.
67. What is the role of the FLASK_ENV environment variable?
  • It indicates the environment the Flask application is running in (e.g., development, production, testing). This can influence how Flask behaves (e.g., enabling debug mode in development).
68. How do you write tests for a Flask application?
  • Flask provides a test client (app.test_client()) that allows you to simulate requests to your application without running a full server. You can use testing frameworks like unittest or pytest to write test cases and assertions.
69. What is the purpose of the Flask test client?
  • The test client allows you to send requests to your application programmatically and inspect the responses (status code, headers, data) for testing purposes.
70. How do you test view functions that require a database connection?
  • You can use an in-memory SQLite database for testing or set up a separate test database.
  • You can use Flask-SQLAlchemy's testing utilities to manage the database session and transactions for tests.
71. How do you test view functions that require a user to be logged in?
  • You can use Flask-Login's testing utilities to simulate a logged-in user in your tests.
72. What is context management in Flask? How do you use with app.app_context(): and with app.test_request_context('/'):?
  • Context management allows you to manually push the application or request context.
    • with app.app_context():: Pushes the application context, making current_app and g available. Useful for running tasks outside of a request (e.g., database creation).
    • with app.test_request_context('/'):: Pushes both the application and request context, simulating a request to a specific URL. Useful for testing code that relies on the request context without making an actual HTTP request.
73. How do you handle caching in Flask?
  • Using an extension like Flask-Caching, which supports various caching backends (memory, Redis, Memcached). You can use decorators to cache the output of view functions or other functions.
74. How do you send emails from a Flask application?
  • Using an extension like Flask-Mail, which provides a simple interface for sending emails through an SMTP server.
75. What is the purpose of the FLASK_APP environment variable?
  • FLASK_APP tells the flask command-line tool which application to run. It should be set to the name of the Python module or file that contains your Flask application instance (e.g., export FLASK_APP=app.py).
76. What is the purpose of the FLASK_DEBUG environment variable? (Older way)
  • FLASK_DEBUG=1 was an older way to enable debug mode. The recommended way now is to set FLASK_ENV=development.
77. How do you configure logging in Flask?
  • Flask's logger is an instance of Python's standard logging.Logger. You can configure it like any other Python logger, setting handlers and formatters.
78. How do you use message flashing in Flask?
  • Using the flash() function to store messages in the session (e.g., flash('Your profile was updated!', 'success')).
  • Retrieving and displaying flashed messages in templates using get_flashed_messages().
79. What are signals in Flask? (Advanced)
  • Signals provide a way for different parts of your application (or extensions) to send and receive notifications without being tightly coupled. Flask provides built-in signals for events like request started, request finished, before request, etc.
80. How do you create a custom command-line interface for your Flask application?
  • Using Flask's built-in CLI integration with Click. You can define custom commands using the @app.cli.command() decorator.
81. How do you handle internationalization (i18n) and localization (l10n) in Flask?
  • Using an extension like Flask-Babel, which provides tools for marking strings for translation, generating translation files, and handling locale-specific formatting.
82. How do you implement pagination in Flask?
  • When querying data from a database, you can use limits and offsets in your SQL queries or ORM calls. Flask-SQLAlchemy's query objects have methods like paginate(). You'll then need to pass pagination information to your template and build pagination links.
83. What are Context Processors in Flask?
  • Context processors are functions that run before rendering a template. They inject variables into the template context, making those variables available in all templates without explicitly passing them in every render_template() call.
84. How do you register a Context Processor?
  • Using the @app.context_processor decorator.
85. What is the purpose of the before_request and after_request decorators?
  • @app.before_request: Decorates a function that runs before every request. Useful for setting up resources or performing checks (e.g., authentication).
  • @app.after_request: Decorates a function that runs after every request, before the response is sent. Useful for modifying the response (e.g., adding headers).
86. What is the purpose of the teardown_request decorator?
  • @app.teardown_request: Decorates a function that runs after every request, even if an exception occurred. Useful for cleaning up resources (e.g., closing database connections).
87. How do you work with cookies in Flask?
  • Setting cookies: Use the response.set_cookie() method on the response object.
  • Accessing cookies: Use request.cookies.
88. What is the difference between cookies and sessions in Flask?
  • Cookies: Small pieces of data stored in the user's browser. Can be accessed and modified by both the server and the client (though Flask's session cookies are signed). Limited in size.
  • Sessions: Data stored on the server-side. The client only receives a session ID (in a cookie) to identify their session. More secure for sensitive data.
89. How do you handle file downloads in Flask?
  • Using the send_file() function from Flask, providing the file path and optional arguments like MIME type and attachment filename.
90. What is the purpose of the @app.cli.command() decorator?
  • This decorator (from Flask's CLI integration) is used to register a function as a custom command that can be executed using the flask command line tool (e.g., flask my-custom-command).
91. How do you define custom filters or tests in Jinja2?
  • You can register custom filters or tests with the Jinja2 environment, typically within your Flask application configuration or using an extension.
92. What is the purpose of the safe filter in Jinja2?
  • The safe filter marks a string as "safe" and prevents Jinja2's automatic escaping of HTML. Use with caution to avoid XSS vulnerabilities when displaying user-provided HTML.
93. How do you handle multiple configuration environments (development, production) in a clean way?
  • Using environment variables (FLASK_ENV).
  • Creating separate configuration classes or files and loading the appropriate one based on the environment.
  • Using an extension like Flask-Environ (though not officially part of Flask).
94. What are some security considerations when building Flask applications?
  • CSRF protection (using Flask-WTF).
  • XSS prevention (Jinja2's auto-escaping helps).
  • Input validation (using Flask-WTF validators).
  • Secure password hashing.
  • Keeping secrets (SECRET_KEY, database credentials) out of source code (using environment variables).
  • Avoiding SQL injection (using an ORM like SQLAlchemy).
  • Using HTTPS in production.
95. How do you deploy a Flask application using Docker?
  • Create a Dockerfile that specifies the base image (Python), copies your application code, installs dependencies, and defines the command to run your WSGI server (e.g., Gunicorn).
  • Build the Docker image.
  • Run the Docker container, potentially with a reverse proxy like Nginx in another container.
96. What are some common patterns for structuring larger Flask applications?
  • Using Blueprints to modularize different parts of the application.
  • Separating concerns (e.g., models in a models.py file, forms in a forms.py file).
  • Using the application factory pattern to create the Flask app instance.
97. Explain the application factory pattern. Why is it useful?
  • The application factory pattern involves creating a function that creates and configures the Flask application instance. It's useful for:
    • Testing: Allows you to create separate app instances for testing.
    • Multiple Instances: Useful if you need to run multiple instances of your app with different configurations.
    • Extensions: Makes it easier to initialize extensions with the app instance.
98. How do you implement background tasks in Flask?
  • Using separate worker processes and message queues (like Redis or RabbitMQ) with libraries like Celery or Redis Queue (RQ). Your Flask app sends tasks to the queue, and the workers process them asynchronously.
99. What is the purpose of the @app.before_first_request decorator? (Older)
  • This decorator was used to run a function only once, before the very first request to the application. It's less common in modern Flask, as setup often happens during application initialization or with the application context.
100. How do you handle scheduled tasks (cron jobs) with a Flask application?
  • You can use standard operating system cron jobs to run Python scripts that interact with your Flask application's code (e.g., by pushing an application context). Alternatively, some task queue libraries (like Celery) have scheduling capabilities.
101. What is the difference between render_template() and send_file()?
  • render_template() processes a Jinja2 template and returns the rendered HTML as a response.
  • send_file() sends a static file from the server to the client as a response.
102. How do you add custom error pages for specific HTTP status codes?
  • Using the @app.errorhandler(status_code) decorator on a view function that returns the custom error page.
103. How do you access the current user in a view function after authentication with Flask-Login?
  • Using the current_user proxy object from Flask-Login.
104. How do you check if a user is authenticated with Flask-Login?
  • Check the is_authenticated property of the current_user object (e.g., if current_user.is_authenticated:).
105. What is the purpose of the app.test_request_context() method?
  • It creates and pushes a request context for testing purposes, allowing you to test code that relies on the request context without making an actual HTTP request.
106. How do you add custom headers to a response?
  • Modify the response.headers dictionary after getting the response object from a view function (e.g., response = make_response(render_template('index.html')); response.headers['X-Custom-Header'] = 'Value'; return response).
107. How do you set cookies in a response?
  • Using the response.set_cookie('cookie_name', 'cookie_value') method.
108. How do you delete cookies?
  • Using response.delete_cookie('cookie_name').
109. What is the maximum size of a cookie?
  • Cookies have size limitations, typically around 4KB.
110. What are signed cookies in Flask?
  • Flask's session cookies are signed by default using the SECRET_KEY. This means the server can detect if the cookie has been tampered with by the client, although the content is not encrypted.
111. How do you handle file storage in Flask (e.g., user avatars)?
  • Store files on the server's file system or use cloud storage services (like AWS S3, Google Cloud Storage). Store file paths or URLs in your database.
112. What is the difference between GET and POST requests?
  • GET: Used to request data from a resource. Data is sent in the URL query string. Should be idempotent and safe (doesn't change server state).
  • POST: Used to submit data to be processed to a specified resource. Data is sent in the request body. Can change server state.
113. What are PUT and DELETE requests?
  • PUT: Used to update a resource or create a new resource at a specific URI. Should be idempotent.
  • DELETE: Used to delete a specified resource.
114. How do you access URL parameters (e.g., /items?category=electronics)?
  • Using request.args.get('category').
115. How do you access path parameters (e.g., /users/123)?
  • These are passed as arguments to the view function (e.g., def get_user(user_id): ...).
116. What is the purpose of the @app.cli.command() decorator?
  • This decorator (from Flask's CLI integration) is used to register a function as a custom command that can be executed using the flask command line tool (e.g., flask my-custom-command).
117. How do you define custom filters or tests in Jinja2?
  • You can register custom filters or tests with the Jinja2 environment, typically within your Flask application configuration or using an extension.
118. What is the purpose of the safe filter in Jinja2?
  • The safe filter marks a string as "safe" and prevents Jinja2's automatic escaping of HTML. Use with caution to avoid XSS vulnerabilities when displaying user-provided HTML.
119. How do you handle multiple configuration environments (development, production) in a clean way?
  • Using environment variables (FLASK_ENV).
  • Creating separate configuration classes or files and loading the appropriate one based on the environment.
  • Using an extension like Flask-Environ (though not officially part of Flask).
120. What are some security considerations when building Flask applications?
  • CSRF protection (using Flask-WTF).
  • XSS prevention (Jinja2's auto-escaping helps).
  • Input validation (using Flask-WTF validators).
  • Secure password hashing.
  • Keeping secrets (SECRET_KEY, database credentials) out of source code (using environment variables).
  • Avoiding SQL injection (using an ORM like SQLAlchemy).
  • Using HTTPS in production.
121. How do you deploy a Flask application using Docker?
  • Create a Dockerfile that specifies the base image (Python), copies your application code, installs dependencies, and defines the command to run your WSGI server (e.g., Gunicorn).
  • Build the Docker image.
  • Run the Docker container, potentially with a reverse proxy like Nginx in another container.
122. What are some common patterns for structuring larger Flask applications?
  • Using Blueprints to modularize different parts of the application.
  • Separating concerns (e.g., models in a models.py file, forms in a forms.py file).
  • Using the application factory pattern to create the Flask app instance.
123. Explain the application factory pattern. Why is it useful?
  • The application factory pattern involves creating a function that creates and configures the Flask application instance. It's useful for:
    • Testing: Allows you to create separate app instances for testing.
    • Multiple Instances: Useful if you need to run multiple instances of your app with different configurations.
    • Extensions: Makes it easier to initialize extensions with the app instance.
124. How do you implement background tasks in Flask?
  • Using separate worker processes and message queues (like Redis or RabbitMQ) with libraries like Celery or Redis Queue (RQ). Your Flask app sends tasks to the queue, and the workers process them asynchronously.
125. What is the purpose of the @app.before_first_request decorator? (Older)
  • This decorator was used to run a function only once, before the very first request to the application. It's less common in modern Flask, as setup often happens during application initialization or with the application context.
126. How do you handle scheduled tasks (cron jobs) with a Flask application?
  • You can use standard operating system cron jobs to run Python scripts that interact with your Flask application's code (e.g., by pushing an application context). Alternatively, some task queue libraries (like Celery) have scheduling capabilities.
127. What is the difference between render_template() and send_file()?
  • render_template() processes a Jinja2 template and returns the rendered HTML as a response.
  • send_file() sends a static file from the server to the client as a response.
128. How do you add custom error pages for specific HTTP status codes?
  • Using the @app.errorhandler(status_code) decorator on a view function that returns the custom error page.
129. How do you access the current user in a view function after authentication with Flask-Login?
  • Using the current_user proxy object from Flask-Login.
130. How do you check if a user is authenticated with Flask-Login?
  • Check the is_authenticated property of the current_user object (e.g., if current_user.is_authenticated:).
131. What is the purpose of the app.test_request_context() method?
  • It creates and pushes a request context for testing purposes, allowing you to test code that relies on the request context without making an actual HTTP request.
132. How do you add custom headers to a response?
  • Modify the response.headers dictionary after getting the response object from a view function (e.g., response = make_response(render_template('index.html')); response.headers['X-Custom-Header'] = 'Value'; return response).
133. How do you set cookies in a response?
  • Using the response.set_cookie('cookie_name', 'cookie_value') method.
134. How do you delete cookies?
  • Using response.delete_cookie('cookie_name').
135. What is the maximum size of a cookie?
  • Cookies have size limitations, typically around 4KB.
136. What are signed cookies in Flask?
  • Flask's session cookies are signed by default using the SECRET_KEY. This means the server can detect if the cookie has been tampered with by the client, although the content is not encrypted.
137. How do you handle file storage in Flask (e.g., user avatars)?
  • Store files on the server's file system or use cloud storage services (like AWS S3, Google Cloud Storage). Store file paths or URLs in your database.
138. What is the difference between GET and POST requests?
  • GET: Used to request data from a resource. Data is sent in the URL query string. Should be idempotent and safe (doesn't change server state).
  • POST: Used to submit data to be processed to a specified resource. Data is sent in the request body. Can change server state.
139. What are PUT and DELETE requests?
  • PUT: Used to update a resource or create a new resource at a specific URI. Should be idempotent.
  • DELETE: Used to delete a specified resource.
140. How do you access URL parameters (e.g., /items?category=electronics)?
  • Using request.args.get('category').
141. How do you access path parameters (e.g., /users/123)?
  • These are passed as arguments to the view function (e.g., def get_user(user_id): ...).