Interview Preparation

Flask Interview Questions

Master the most commonly asked interview questions with comprehensive, expert-crafted answers designed to help you succeed.

24
Questions
100%
Expert Answers
Q1
What is Flask?

Flask is a lightweight and flexible micro web framework written in Python. It is designed to make getting started quick and easy, with the ability to scale up to complex applications.

Flask is based on the WSGI (Web Server Gateway Interface) toolkit and the Jinja2 templating engine. It does not enforce dependencies or project layouts, allowing developers to structure their projects as they prefer.

Flask is ideal for small to medium-sized applications and provides features like built-in development server, debugger, RESTful request dispatching, and more.

Q2
What are the features of Flask Python?
  • Built-in Development Server and Debugger: Makes testing and debugging easier during development.
  • Compatibility with Modern Technologies: Works well with front-end frameworks, databases, and APIs.
  • Highly Scalable: Suitable for both simple and large web applications due to its minimalistic core.
  • Unit Testing Support: Includes tools to write and test small units of code.
  • Client-Side Sessions: Securely stores data in browser cookies with Flask’s session management.
  • RESTful Request Dispatching: Easy handling of REST APIs using decorators and route management.
  • Google App Engine Compatibility: Can be deployed easily on GCP’s App Engine.
  • Unicode Support: Works with international character sets by default.
  • WSGI Compliance: Fully compliant with the Python WSGI standard.
Q3
What is the difference between Flask and Django?

Flask and Django are two popular web frameworks in Python, but they differ significantly in terms of architecture, flexibility, and features.

AspectFlaskDjango
TypeWSGI micro frameworkFull-stack web framework
Database SupportSupports multiple databasesLimited database support (primarily ORM)
ORMUses SQLAlchemyHas built-in ORM
ArchitectureDiversified, modularMonolithic
Project StructureArbitrary/flexibleConventional and structured
API SupportBuilt-in support for APIsRequires Django REST Framework for API support
Dynamic HTML PagesLimited supportFull support for dynamic pages
Visual DebuggingSupportedNot supported
Bootstrapping ToolNot includedDjango-admin included for scaffolding projects
URL DispatcherRESTful request styleUses robust documentation and URL patterns
Q4
What is the default host and port of Flask?

When running a Flask application using the built-in development server, it binds to the following defaults:

  • Default Host: 127.0.0.1 (localhost)
  • Default Port: 5000

This means by default, the Flask app is accessible only on the local machine using the URL http://127.0.0.1:5000.

If you want to change the host or port, you can specify them when calling app.run() like this:

app.run(host='0.0.0.0', port=8000)
Q5
Why do we use Flask(__name__) in Flask?

Answer: The __name__ parameter is a built-in Python variable that gets its value depending on how the script is executed.

When passed to the Flask constructor like this: Flask(__name__), it tells Flask the name of the application’s module or package. This is essential because:

  • Resource Location: It helps Flask locate templates, static files, and other resources relative to the application's location.
  • Application Discovery: It allows Flask to understand whether the script is run directly or imported as a module, which is important for enabling debugging and reloading features.

This enables Flask to configure paths and serve content correctly during development and deployment.

Q6
What is routing in Flask?

Answer: Routing in Flask refers to the technique of mapping specific URLs (routes) to functions in the backend that handle the logic and return responses.

It allows users to access different parts of a web application through clean and descriptive URLs. Flask provides the @app.route() decorator to bind a URL to a specific view function.

Example:

@app.route('/hello')
def hello():
    return 'Hello, World!'

If your site is www.example.org, then accessing www.example.org/hello will trigger the hello() function. This makes URLs more user-friendly and easier to navigate.

Q7
What is Template Inheritance in Flask?

Template Inheritance in Flask is a feature provided by the Jinja templating engine, allowing developers to avoid repeating common HTML structures like headers, footers, or navigation bars on multiple pages.

By defining a base template containing these common elements and using block placeholders, child templates can inherit and override only the necessary sections, ensuring a DRY (Don't Repeat Yourself) approach.

Q8
What does url_for do in Flask?

The url_for() function dynamically generates a URL for a given function name and arguments. This avoids hardcoding URLs, making the code more maintainable.

<a href="{{ url_for('get_post_id', post_id=post.id) }}">{{ post.title }}</a>

@app.route("/blog/post/<string:post_id>")
def get_post_id(post_id):
    return post_id
  
Q9
How do you handle cookies in Flask?

Cookies in Flask can be set using the set_cookie() method on a response object. These cookies are stored on the client’s machine and sent with each request until they expire or are deleted.

from flask import make_response

@app.route('/set_cookie')
def set_cookie():
    resp = make_response("Cookie Set")
    resp.set_cookie('username', 'John Doe')
    return resp
  
Q10
How does file uploading work in Flask?

File uploading in Flask requires an HTML form with enctype="multipart/form-data". Uploaded files are accessed via request.files and can be saved to the server.

from flask import request

file = request.files['file']
file.save("/path/to/save/" + file.filename)
  
Q11
What is Flask-WTF, and what are its characteristics?

Flask-WTF is an extension for integrating WTForms into Flask applications, offering form rendering, validation, and CSRF protection.

  • Integration with WTForms for building forms
  • Built-in CSRF protection
  • Internationalization support
  • Captcha integration
  • File uploading support with Flask-Uploads
Q12
How long can an identifier be in Flask Python?

In Python (and thus Flask), identifiers can be of any length but must follow naming rules: start with a letter or underscore, and be followed by letters, digits, or underscores.

Python is case-sensitive, and reserved keywords (e.g., def, class, return) cannot be used as identifiers.

Q13
What are Flask’s request and response hooks?

Flask provides request and response hooks that allow you to run functions before or after a request is processed. These hooks can be used for tasks like setting up resources, authentication checks, or modifying responses.

  • before_request: Runs before each request. Commonly used for setting up session data or checking user authentication.
  • after_request: Runs after each request, receiving the response object so you can modify it before sending it to the client.
  • teardown_request: Runs after the response has been sent, useful for cleanup operations like closing database connections.
@app.before_request
def before():
    print("Before request")

@app.after_request
def after(response):
    print("After request")
    return response
  
Q14
How can you protect a Flask application from CSRF attacks?

CSRF (Cross-Site Request Forgery) attacks can be prevented in Flask by using the Flask-WTF extension, which integrates with WTForms to provide CSRF protection.

Flask-WTF adds a hidden CSRF token to forms and validates it on submission. This ensures that the form submission originates from the authenticated user and not from a malicious site.

from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired

class MyForm(FlaskForm):
    name = StringField('Name', validators=[DataRequired()])
    submit = SubmitField('Submit')
  

Make sure to set a secret key for CSRF protection:

app.config['SECRET_KEY'] = 'your_secret_key'
  
Q15
What does 'WSGI' mean, and why is it important for Flask?

WSGI stands for Web Server Gateway Interface. It’s a specification that defines how a web server communicates with Python web applications and how these applications can be chained together to handle a single request.

WSGI is important for Flask because it provides a standard interface between the web server (like Apache, Nginx) and the Flask application, allowing Flask to be deployed across various environments without being tied to a specific server implementation.

Popular WSGI servers for Flask include Gunicorn and uWSGI.

Q16
How do you create a simple 'Hello, World!' application in Flask?

To create a simple Flask application that displays Hello, World!, follow these steps:

  1. Install Flask: pip install Flask
  2. Create a Python file (e.g., app.py) with the following code:
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

if __name__ == '__main__':
    app.run(debug=True)
  

3. Run the application: python app.py

4. Open your browser at http://127.0.0.1:5000/ to see the message.

Q17
What is Jinja2, and how does Flask use it?

Jinja2 is a templating engine for Python that lets you embed variables and control structures directly into HTML or other text formats.

Flask uses Jinja2 to render templates, allowing developers to pass data from Python code into HTML pages. Variables are represented with {{ }} and control structures like loops and conditionals use {% %}.

# Example in Flask
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/user/<username>')
def profile(username):
    return render_template('profile.html', name=username)
  

Inside profile.html, you can use {{ name }} to display the username dynamically.

Q18
How can you create dynamic web pages with Flask?

Dynamic pages in Flask are created using:

  • Routes (@app.route): Map URLs to Python functions.
  • Jinja2 templates: Embed Python variables and logic into HTML.

Example:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/user/<username>')
def profile(username):
    return render_template('profile.html', name=username)
  

In profile.html:

<h1>Hello, {{ name }}!</h1>
  
Q19
What is a Flask extension? Give an example.

A Flask extension is a package that adds extra functionality to Flask applications, such as database integration, form handling, or authentication.

Example: Flask-SQLAlchemy simplifies working with SQL databases in Flask.

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)

    def __repr__(self):
        return f'<User %r>' % self.username

with app.app_context():
    db.create_all()
    admin = User(username='admin')
    db.session.add(admin)
    db.session.commit()
    print(User.query.all())
  
Q20
What is the purpose of the 'app.run()' method in Flask?

The app.run() method starts Flask’s built-in development server, enabling the application to listen for incoming HTTP requests.

Key functions:

  • Binds to a specified host and port (default: 127.0.0.1:5000).
  • Starts a Werkzeug WSGI server, the underlying HTTP server Flask uses.
  • Begins handling requests according to the routes and view functions you have defined.

Note: It’s intended for development only. For production, use a production-ready WSGI server like Gunicorn or uWSGI.

Q21
What are the different HTTP methods, and how do you handle them in Flask routes?

HTTP methods (verbs) specify the desired action to perform on a resource. Common ones include:

  • GET – Retrieve data
  • POST – Create new data
  • PUT – Update existing data
  • DELETE – Remove data
  • PATCH – Partially update a resource

In Flask, you define the allowed methods using the methods argument in the @app.route() decorator.

from flask import Flask, request

app = Flask(__name__)

@app.route('/data', methods=['GET', 'POST'])
def data_route():
    if request.method == 'POST':
        # Handle POST request
        return 'Data created!', 201
    else:
        # Handle GET request
        return 'Data retrieved!', 200

if __name__ == '__main__':
    app.run(debug=True)
  
Q22
How do you use sessions in Flask to store user data?

Flask sessions allow you to store data across requests for a specific user. Session data is stored on the client as a secure cookie, signed with the application's secret_key to prevent tampering.

Steps to use sessions:

  1. Set app.secret_key to a secure random value.
  2. Import and use the session object from flask like a dictionary.
from flask import Flask, session

app = Flask(__name__)
app.secret_key = 'supersecretkey'

@app.route('/set_session')
def set_session():
    session['username'] = 'JohnDoe'
    return 'Session data set!'

@app.route('/get_session')
def get_session():
    username = session.get('username', 'Guest')
    return f'Hello, {username}!'

if __name__ == '__main__':
    app.run(debug=True)
  

Sessions are especially useful for persisting login information, user preferences, or temporary data between requests.

Q23
How can you structure a Flask application into multiple files or folders?

You can structure a Flask application into multiple files and folders using blueprints or packages.

  • Blueprints: Let you organize related views, routes, and logic in separate files (e.g., users.py, products.py) and register them with the main Flask app.
  • Packages: Organize the app into a directory structure with an __init__.py that creates and configures the app, plus submodules for views, models, etc.

Example structure:

my_app/
├── __init__.py
├── models.py
├── views/
│   ├── __init__.py
│   ├── user_views.py
│   └── product_views.py
├── templates/
│   ├── users/
│   └── products/
└── static/
  

Using this approach improves maintainability, scalability, and code organization.

Q24
Explain how to connect a Flask application to a database.

Flask can connect to databases either directly (e.g., sqlite3, psycopg2) or using an ORM like Flask-SQLAlchemy for more convenience.

Using Flask-SQLAlchemy:

  1. Install: pip install Flask-SQLAlchemy
  2. Set the database URI in configuration.
  3. Create models by inheriting from db.Model.
  4. Run db.create_all() to create tables.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///your_database.db'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)

with app.app_context():
    db.create_all()
    new_user = User(username='admin')
    db.session.add(new_user)
    db.session.commit()
  

Flask-SQLAlchemy abstracts SQL queries into Python classes and methods, making database operations more intuitive.

Why Choose Our Question Bank?

Get access to expertly crafted answers and comprehensive preparation materials

Complete Collection

Access all 24 carefully curated questions covering every aspect of Flask interviews

Expert Answers

Get detailed, professional answers crafted by industry experts with real-world experience

Instant Access

Start preparing immediately with instant access to all questions and answers after sign-up