Google News
logo
Flask Interview Questions
Flask is an API of Python that allows us to build up web-applications. It was developed by Armin Ronacher. Flask’s framework is more explicit than Django’s framework and is also easier to learn because it has less base code to implement a simple web-Application. A Web-Application Framework or Web Framework is the collection of modules and libraries that helps the developer to write applications without writing the low-level codes such as protocols, thread management, etc. Flask is based on WSGI(Web Server Gateway Interface) toolkit and Jinja2 template engine.
Flask Python is one of the newest frameworks of Python and is used for designing web applications for the following features :
 
* Flask comes with built-in development server as well as fast debugger
* It is based on Unicode.
* Python Flask is extensively documented.
* It also contains the integrated support required for unit testing
* It has the feature of restful request dispatching
* Comes with Jinja2 templating technique
* Flask supports secure cookies i.e. client-side sessions
* Also has the WSGI 1.0 compliant feature.
Flask Python comes with all the advantages of Python and some additional pros of it are :
 
* Flasks design is lightweight and modular. Therefore, it is easy to transform it into the web applications or framework when one needs very few extensions without weighing much.
* Flask is ORM-agnostic : i.e. user can plug in their favorite ORM like SqlAlchemy
* The basic foundation of API is very nicely shaped and made coherent.
* Documentation of flask is very comprehensive, filled with lots of examples and are well structured. Users can even try out some sample applications to really get the real feel of Flask.
* It is very easy to deploy Flask in production as Flask comes with 100% WSGI 1.0 compliant
* Flask can handle HTTP request easily with help of its functionalities
* It is highly flexible. Its configuration is even more flexible than that of Django, which gives its users plenty of solutions for every product they need.
Flask is part of the micro-framework. Which means it will have little to no dependencies on external libraries. It makes the framework light while there is little dependency to update and less security bugs.
The development version of the Flask framework can be obtained using the below-mentioned commands.
 
cd flask && python3 setup.py develop
Flask is a “microframework” primarily build for a small application with simpler requirements. In flask, you have to use external libraries. Flask is ready to use.
 
Pyramid are build for larger applications. It provides flexibility and lets the developer use the right tools for their project. The developer can choose the database, URL structure, templating style and more. Pyramid is heavy configurable.
 
Like Pyramid, Django can also used for larger applications. It includes an ORM.
A session basically allows you to remember information from one request to another. In a flask, it uses a signed cookie so the user can look at the session contents and modify. The user can modify the session if only it has the secret key Flask.secret_key.
Flask-WTF is featured to offer simple integration with WTForms. The Features include for Flask WTF are :
 
* Provides Integration with web forms
* Is very secure form as it comes with CSRF token
* Provides global CSRF protection
* Comes with internationalization integration
* Also features Recaptcha supporting
* Contains File upload that closely works with Flask Uploads
Flask default host and port can be changed by passing the values to host and port parameters while calling run method on the app.
 
from flask import Flask
app = Flask(__name__)
 
@app.route("/")
def index():
    return "Hello, World!"
 
if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8080)

 

HTTP methods are used to retrieve data from an URL :
 
GET : The GET is the method that sends data to the server unencrypted.
HEAD :  HEAD is similar to GET, but that it has no response body.
POST : The POST server does not cache the HTML form data that it sends
PUT : It is the method in which the uploaded content replaces current data representations of the target resources.
DELETE : This method removes the current representations of the target resource that is suggested by a URL.
Flask can be stated as a micro framework, which is solely built for a small application, which has simpler requirements. In flask, the users have to use external libraries. Flask is always ready to use.
 
Pyramid, on the other hand, is built for larger application as it provides flexibility and allows the developer use the right features for their project. The developer can choose the database, templating style URL structure and more. Pyramid is therefore heavy configurable.
Flask uses thread local objects internally so that user don’t have to pass objects around from function to function within a request in order to stay threadsafe. This approach is useful, but it requires a valid request context for dependency injection or when attempting to reuse code which uses a value pegged to the request.
Flask supports database powered application (RDBS). Such system requires creating a schema, which requires piping the shema.sql file into a sqlite3 command. So you need to install sqlite3 command in order to create or initiate the database in Flask.
Follow the below-mentioned steps to deploy the python flask app on Heroku :
 
* Create a virtual environment with pipenv and install Flask and Gunicorn . - $ pipenv install 
* Create a “Procfile” and write the following code. - $ touch Procfile flask gunicorn 
* Create “runtime.txt” and write the following code. - $ touch runtime.txt 
* Create a folder named “app” and enter the folder. - $ mkdir app, $ cd app
* Create a python file, “main.py” and enter the sample code. -  touch main.py 
* Get back to the previous directory “eflask”.Create a file“wsgi.py” and insert the following code. -$ cd ../ , $ touch wsgi.py
* Run the vitual environment. -$ pipenv shell
* Initialize an empty repo, add the files in the repo and commit all the changes.- $ git init, $ git add .
* - $ git commit -m "Initial Commit" 
* Login to heroku CLI using - heroku login
* Now, Create a unique name for your Web app. -$ heroku create eflask-app
* Push your code from local to the heroku remote. -$ git push heroku master
Flask framework allows to its users to request database in three ways. They are :
 
before_request() : These connections are called before making a request and no arguments are passed
after_request() : These connections are called after making a request and response is passed that will be sent to the client.
teardown_request() : These connections are called in a situation where an exception is raised and the response are not sure to get. They are also called after the construction of response. These are not allowed to change the request, and their values can be ignored.
Flask’s url_for function helps in creating dynamic routes. We can make use of url_for in the Flask templates. We can call the view function with parameters and values to generate URLs.
 
For example, pass a function and its arguments, as shown below.
 
<a href=”{{ url_for(‘get_post_id’, post_id=post.id}}”>{{post.title}}<a>

View function for handling variables in routes.
 
@app.route(“/blog/post/<string:post_id>”)
def get_post_id(post_id):
return post_id

 

We can create an Admin interface in Flask using the Flask-Admin extension. It helps in grouping individual views together in classes. We can use the Flask-Appbuilder extension too. Flask-Appbuilder already comes with an Admin interface.
To integrate with Flask, we can make use of a Flask extension called Flask-Social. It not only helps in authenticating users from Twitter but also other social platforms or accounts such as Facebook and Google. We need to use Flask-Social along with Flask-Security.
 
We need to install individual API libraries in Python and also need to get consumer and secret keys by registering the Flask application on the external account providers.
There are two ways by which users can enable debugging in Flask. They are :
 
* By setting the flag on the applications object
* By passing the flag as a parameter to run. If the user is enabling to debug support, the server will reload it when the code will change and the user doesn’t have to restart after each change made in the code.
Flask Python makes use of thread local objects internally so that the user doesn’t have to pass objects around from one function to another function within a request so as to stay thread safe. This approach is quite useful, but it requires a pure request context for dependency injection or while attempting to reuse code, which uses a value indulged in the requests.
 
Flask Python supports all kinds of database-powered applications like RDBS. Such systems require creating of a schema, which further requires connecting the schema.sql file to a sqlite3 command. So users need to install sqlite3 command if they want to create or start the database in Flask Python.
g” is data shared between different parts of the code base within one request cycle. For example, a database connection or the user that is currently logged in. While "session" provides you a storage place to store data for a specific browser. Which means using a specific browser, returns for more request.
You can take advantage of Flask.before_request hook to log the request body in python flask. Here is an example :
 
@app.before_request
def log_request_info():
    app.logger.debug('Headers: %s', request.headers)
    app.logger.debug('Body: %s', request.get_data())

 

To create an array with checkboxes in Flask you have to create your checkbox input names with the same name.
 
Below is an example which demonstrates how to create an array with checkboxes in Flask
 
<input type="checkbox" value="X" class="danger" name='my_checkbox'>
<input type="checkbox" value="Y" class="danger" name='my_checkbox'>
<input type="checkbox" value="Z" class="danger" name='my_checkbox'>
 
In Flask code you can get selected checkbox values as
 
print(request.form.getlist('my_checkbox'))

Above code outputs value of all selected checkboxes
g is an object provided by Flask. It is a global namespace for holding any data you want during a single app context. For example, a before_request handler could set g.user, which will be accessible to the route and other functions.
 
from flask import g
@app.before_request
def load_user():
    user = User.query.get(request.session.get("user_id"))
    g.user = user

@app.route("/admin")
def admin():
    if g.user is None or not g.user.is_admin:
        return redirect(url_for("index"))

 

In Flask, flask.request.headers is used to get http headers.
 
Example : 
app = flask.Flask(__name__)
@app.route("/")
def index():
    headers = flask.request.headers
    return "Request headers:\n" + str(headers)

app.run(host="127.1.0.1", port=8080)​

 

A WSGI middleware component is a Python callable that is itself a WSGI application, but may handle requests by delegating to other WSGI applications. These applications can themselves be WSGI middleware components.
 
A middleware component can perform such functions as :
 
* Routing a request to different application objects based on the target URL, after changing the environment variables accordingly.
* Allowing multiple applications or frameworks to run side-by-side in the same process
* Load balancing and remote processing, by forwarding requests and responses over a network
* Performing content post-processing, such as applying XSLT stylesheets
A template is a file that contains two types of data, i.e., static and dynamic. Dynamic data in a template is populated during run time. Flask makes use of Jinja2 template engine to let developers create HTML templates with placeholders for dynamic data.
 
These placeholders can be filled during run time by using Flask’s render_template method with required parameters and values.
In Flask, thread-safety has been provided out of the box. We can use objects such as current_app, g, and request without worrying about problems related to locking and concurrency. Moreover, we need not pass objects from methods to methods, and these objects are generally available within a valid request context.
 
This attribute of Flask makes it a bit unique and provides a lot of convenience to the Flask developers while keeping Flask application thread-safe.
Forms in Flask can be implemented by using an extension called Flask-WTF. Flask-WTF is created by integrating Flask with WTForms. WTForms is a python-based form rendering and validation library. It supports data validation, internationalization, and CSRF protection.
 
Flask-WTF also provides reCAPTCHA support along with file uploads when tied with Flask-Uploads. You also can handle JavaScript requests, and customize the error response.
A session in Flask Python is a feature that allows one to remember the information from one request to another. In a flask program, it makes use of a signed cookie so that the user can look at the contents of the session and modify them. The user can also modify the sessions if and only if it has the secret key called the Flask.secret_key. Flask is a small form of Python framework, which behaves the same as the MVC framework. So MVC is a perfect match for Flask.
A decorator is defined as a function that adds functionality to another function without changing it. It wraps the function to add some functionality to it.Some PDB commands include
 
<b> : It adds a breakpoint
<c> : It resumes the execution
<s> : It debugs step by step
<n> : It moves to next line
<l> : It lists the source code
<p> : It prints an expression
Static files should be added to the flasks/static directory and then the files are referenced in the HTML to serve the static files. Static files such as CSS and JavaScript acts as a template and adds more functions to your web application. All the static files are added to the flask/static directory and referenced by the following line to serve it.
//referencing static files in the flask
url_for(‘static’, filename=’static_file_name’)

 

The query string is a key/value pair that is sent by the client to the server in the web URL. These values are actually a part of the URL as a string of parameters and values. To get and work with the query string, we need to use the import request method from the flask.
//example of getting a query string in the Flask
from flask import request   //request method is used to work with the query string values
@app.route("/query")
def query():
args = request.args     //here, we get the query string object in a variable called ‘args’ using 
print(args)

 

To make a portable and serialized representations of Python objects, we have the module known as pickle which accepts a Python object (basically everything in Python is an object) and then converts it into a string type, and after that uses the dump () function to dump it into a file. We term this as pickling. On the contrary, retrieving objects from the stored string forms is called as unpickling.
We can create a form for file uploading by using following code:
 
<html>  
   <body>  
           <form action = "http://localhost:5000/uploader" method = "POST" enctype = "multipart/form-data">  
             <input type = "file" name = "file" />  
             <input type = "submit"/>  
           </form>          
   </body>  
</html>

 

The application context in Flask relates to the idea of a complete request/response cycle. It keeps a track of application-level data during a request or a CLI command. We make use of g and current_app proxies to achieve the same.
 
There are situations when it is difficult to directly import the Flask app, such as in the case of a Flask extension or a Blueprint. Moreover, introducing applications may raise the problem of circular imports.
 
Flask pushes the application context with each request. Therefore, during a request, functions have access to g and current_app to overcome the problem highlighted above.
A RESTful application can be created in Flask with the help of many extensions.
 
Some proven Flask extensions are listed below.
 
* Flask-API
* Flask-RESTful
* Flask-RESTX
* Connexion

However, we need to evaluate these extensions and see which one is more appropriate based on our project requirements and constraints.
Flask Python supports all kinds of database-powered applications like RDBS. Such systems require creating of a schema, which further requires connecting the schema.sql file to a sqlite3 command. So users need to install sqlite3 command if they want to create or start the database in Flask Python.
You can use the import statement to import functions from other files into the main file in the Flask. You can also use the 'from' statement with the 'import' statement to import a specific function from other files into your main flask file.
 
//example of importing functions
from otherFile import function  //importing function method from the file otherFile.py
@app.route("/")
@app.route("/index")
def index():
    baz = function()     //the function imported from your file otherFile.py
if __name__ == '__main__':
    app.run(debug=True)

 

Flask comes with a development server, and the development server has a Debug Mode. The Debug mode can be set to true when we call the run method of the Flask Application object.

Example :
from flask import Flask 
app = Flask(__name__)
app.run(host='127.0.0.1', debug=True)
However, we need to disable the debug mode before deploying the application on production to avoid full stack trace display in the browser. Such a stack trace can reveal a lot of essential details and is prone to exploitation by bad actors.
 
Further, we can make use of the Flask-DebugToolbar extension for easy debugging in the browser. We can also make use of Python’s pdb module and the debugging statement import pdb;pdb.set_trace() to support the debugging process.
When you create the form, you can disable the CSRF for a view with flask-wtf for a restapi by using the following statement.
form = myForm(request.form, csrf_enabled=False)

 

You can create an overall package and add an __init__.py file under the package folder where you declare all the global variables that you need to share between the classes. Then, you should add the code "app = Flask(__name__)" in the __init__.py file. Now you can share and use the app variables anywhere if you just import the package name.
A simple Flask application looks like below
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'
You can start the python flask app by running the below command
$ export FLASK_APP=hello.py
$ flask run
 * Running on http://127.0.0.1:5000/
current_user.get_id() is used to get logged in user id in flask.
 
Here is an example :
from flask import g
if current_user.is_authenticated():
        g.user = current_user.get_id()
Set app.debug to True and add the below code in your function where you want to enable logging in Flask.
import logging
from flask import Flask
app = Flask(__name__)

@app.route('/')
def foo():
    app.logger.warning('A warning occurred')
    app.logger.error('An error occurred')
    app.logger.info('Info')
    return "foo"

 

Use jsonify() function to return json in flask.
 
Example : 
from flask import jsonify
@app.route('/users')
def users():
   users= User.query.all()  
    return jsonify(users)