Flask interview questions
13 questions with answers. 147 open jobs in India ask for Flask.
Can Flask have optional URL parameters?
Another way is to write
@user.route('/<user_id>', defaults={'username': None}) @user.route('/<user_id>/<username>') def show(user_id, username): passBut I guess that you want to write a single route and mark
usernameas optional? If that's the case, I don't think it's possible.From Stack Overflow: asked by Noor, answered by Audrius Kažukauskas (CC BY-SA 3.0)
json.dumps vs flask.jsonify
The
jsonify()function in flask returns aflask.Response()object that already has the appropriate content-type header 'application/json' for use with json responses. Whereas, thejson.dumps()method will just return an encoded string, which would require manually adding the MIME type header.See more about the
jsonify()function here for full reference.Edit: Also, I've noticed that
jsonify()handles kwargs or dictionaries, whilejson.dumps()additionally supports lists and others.From Stack Overflow: asked by Sergei Basharov, answered by Kenneth Wilke (CC BY-SA 4.0)
Can I serve multiple clients using just Flask app.run() as standalone?
flask.Flask.runaccepts additional keyword arguments (**options) that it forwards towerkzeug.serving.run_simple- two of those arguments arethreaded(a boolean) andprocesses(which you can set to a number greater than one to have werkzeug spawn more than one process to handle requests).threadeddefaults toTrueas of Flask 1.0, so for the latest versions of Flask, the default development server will be able to serve multiple clients simultaneously by default. For older versions of Flask, you can explicitly passthreaded=Trueto enable this behaviour.For example, you can do
if __name__ == '__main__': app.run(threaded=True)to handle multiple clients using threads in a way compatible with old Flask versions, or
if __name__ == '__main__': app.run(threaded=False, processes=3)to tell Werkzeug to spawn three processes to handle incoming requests, or just
if __name__ == '__main__': app.run()to handle multiple clients using threads if you know that you will be using Flask 1.0 or later.
That being said, Werkzeug's
serving.run_simplewraps the standard library'swsgirefpackage - and that package contains a reference implementation of WSGI, not a production-ready web server. If you are going to use Flask in production (assuming that "production" is not a low-traffic internal application with no more than 10 concurrent users) make sure to stand it up behind a real web server (see the section of Flask's docs entitled Deployment Options for some suggested methods).From Stack Overflow: asked by ATOzTOA, answered by Sean Vieira (CC BY-SA 4.0)
What are Flask Blueprints, exactly?
A blueprint is a template for generating a "section" of a web application. You can think of it as a mold:
You can take the blueprint and apply it to your application in several places. Each time you apply it the blueprint will create a new version of its structure in the plaster of your application.
# An example from flask import Blueprint tree_mold = Blueprint("mold", __name__) @tree_mold.route("/leaves") def leaves(): return "This tree has leaves" @tree_mold.route("/roots") def roots(): return "And roots as well" @tree_mold.route("/rings") @tree_mold.route("/rings/<int:year>") def rings(year=None): return "Looking at the rings for {year}".format(year=year)This is a simple mold for working with trees - it says that any application that deals with trees should provide access to its leaves, its roots, and its rings (by year). By itself, it is a hollow shell - it cannot route, it cannot respond, until it is impressed upon an application:
from tree_workshop import tree_mold app.register_blueprint(tree_mold, url_prefix="/oak") app.register_blueprint(tree_mold, url_prefix="/fir") app.register_blueprint(tree_mold, url_prefix="/ash")Once it is created it may be "impressed" on the application by using the
register_blueprintfunction - this "impresses" the mold of the blueprint on the application at the locations specified byurl_prefix.From Stack Overflow: asked by JoshieSimmons, answered by Sean Vieira (CC BY-SA 4.0)
When should Flask.g be used?
Advanced Flask Patterns, as linked by Markus, explains some of the changes to
gin 0.10:gnow lives in the application context.- Every request pushes a new application context, wiping the old one, so
gcan still be used to set flags per-request without change to code. - The application context is popped after
teardown_requestis called. (Armin's presentation explains this is because things like creating DB connections are tasks which setup the environment for the request, and should not be handled insidebefore_requestandafter_request)
From Stack Overflow: asked by Yaniv Aknin, answered by theY4Kman (CC BY-SA 4.0)
What is the purpose of Flask's context stacks?
Multiple Apps
The application context (and its purpose) is indeed confusing until you realize that Flask can have multiple apps. Imagine the situation where you want to have a single WSGI Python interpreter run multiple Flask application. We're not talking Blueprints here, we're talking entirely different Flask applications.
You might set this up similar to the Flask documentation section on "Application Dispatching" example:
from werkzeug.wsgi import DispatcherMiddleware from frontend_app import application as frontend from backend_app import application as backend application = DispatcherMiddleware(frontend, { '/backend': backend })Notice that there are two completely different Flask applications being created "frontend" and "backend". In other words, the
Flask(...)application constructor has been called twice, creating two instances of a Flask application.Contexts
When you are working with Flask, you often end up using global variables to access various functionality. For example, you probably have code that reads...
from flask import requestThen, during a view, you might use
requestto access the information of the current request. Obviously,requestis not a normal global variable; in actuality, it is a context local value. In other words, there is some magic behind the scenes that says "when I callrequest.path, get thepathattribute from therequestobject of the CURRENT request." Two different requests will have a different results forrequest.path.In fact, even if you run Flask with multiple threads, Flask is smart enough to keep the request objects isolated. In doing so, it becomes possible for two threads, each handling a different request, to simultaneously call
request.pathand get the correct information for their respective requests.Putting it Together
So we've already seen that Flask can handle multiple applications in the same interpreter, and also that because of the way that Flask allows you to use "context local" globals there must be some mechanism to determine what the "current" request is (in order to do things such as
request.path).Putting these ideas together, it should also make sense that Flask must have some way to determine what the "current" application is!
You probably also have code similar to the following:
from flask import url_forLike our
requestexample, theurl_forfunction has logic that is dependent on the current environment. In this case, however, it is clear to see that the logic is heavily dependent on which app is considered the "current" app. In the frontend/backend example shown above, both the "frontend" and "backend" apps could have a "/login" route, and sourl_for('/login')should return something different depending on if the view is handling the request for the frontend or backend app.To answer your questions...
What is the purpose of the "stack" when it comes to the request or application context?
From the Request Context docs:
Because the request context is internally maintained as a stack you can push and pop multiple times. This is very handy to implement things like internal redirects.
In other words, even though you typically will have 0 or 1 items on these stack of "current" requests or "current" applications, it is possible that you could have more.
Read the rest at the sourceFrom Stack Overflow: asked by Ben Davis, answered by Mark Hildreth (CC BY-SA 3.0)
Why does running the Flask dev server run itself twice?
The Werkzeug reloader spawns a child process so that it can restart that process each time your code changes. Werkzeug is the library that supplies Flask with the development server when you call
app.run().See the
restart_with_reloader()function code; your script is run again withsubprocess.call().If you set
use_reloadertoFalseyou'll see the behaviour go away, but then you also lose the reloading functionality:app.run(port=4004, debug=config.DEBUG, host='0.0.0.0', use_reloader=False)You can disable the reloader when using the
flask runcommand too:FLASK_DEBUG=1 flask run --no-reloadYou can use the
werkzeug.serving.is_running_from_reloaderfunction if you wanted to detect when you are in the reloading child process:from werkzeug.serving import is_running_from_reloader if is_running_from_reloader(): print(f"################### Restarting @ {datetime.utcnow()} ###################")However, if you need to set up module globals, then you should instead use the
@app.before_first_requestdecorator on a function and have that function set up such globals. It'll be called just once after every reload when the first request comes in:@app.before_first_request def before_first_request(): print(f"########### Restarted, first request @ {datetime.utcnow()} ############")Do take into account that if you run this in a full-scale WSGI server that uses forking or new subprocesses to handle requests, that
before_first_requesthandlers may be invoked for each new subprocess.From Stack Overflow: asked by kramer65, answered by Martijn Pieters (CC BY-SA 4.0)
Are global variables thread-safe in Flask? How do I share data between requests?
You can't use global variables to hold this sort of data. Not only is it not thread safe, it's not process safe, and WSGI servers in production spawn multiple processes. Not only would your counts be wrong if you were using threads to handle requests, they would also vary depending on which process handled the request.
Use a data source outside of Flask to hold global data. A database, memcached, or redis are all appropriate separate storage areas, depending on your needs. If you need to load and access Python data, consider
multiprocessing.Manager. You could also use the session for simple data that is per-user.The development server may run in single thread and process. You won't see the behavior you describe since each request will be handled synchronously. Enable threads or processes and you will see it.
app.run(threaded=True)orapp.run(processes=10). (In 1.0 the server is threaded by default.)Some WSGI servers may support gevent or another async worker. Global variables are still not thread safe because there's still no protection against most race conditions. You can still have a scenario where one worker gets a value, yields, another modifies it, yields, then the first worker also modifies it.
If you need to store some global data during a request, you may use Flask's
gobject. Another common case is some top-level object that manages database connections. The distinction for this type of "global" is that it's unique to each request, not used between requests, and there's something managing the set up and teardown of the resource.From Stack Overflow: asked by sayantankhan, answered by davidism (CC BY-SA 4.0)
What is an 'endpoint' in Flask?
How Flask Routing Works
The entire idea of Flask (and the underlying Werkzeug library) is to map URL paths to some logic that you will run (typically, the "view function"). Your basic view is defined like this:
@app.route('/greeting/<name>') def give_greeting(name): return 'Hello, {0}!'.format(name)Note that the function you referred to (add_url_rule) achieves the same goal, just without using the decorator notation. Therefore, the following is the same:
# No "route" decorator here. We will add routing using a different method below. def give_greeting(name): return 'Hello, {0}!'.format(name) app.add_url_rule('/greeting/<name>', 'give_greeting', give_greeting)Let's say your website is located at 'www.example.org' and uses the above view. The user enters the following URL into their browser:
http://www.example.org/greeting/MarkThe job of Flask is to take this URL, figure out what the user wants to do, and pass it on to one of your many python functions for handling. It takes the path:
/greeting/Mark...and matches it to the list of routes. In our case, we defined this path to go to the
give_greetingfunction.However, while this is the typical way that you might go about creating a view, it actually abstracts some extra info from you. Behind the scenes, Flask did not make the leap directly from URL to the view function that should handle this request. It does not simply say...
URL (http://www.example.org/greeting/Mark) should be handled by View Function (the function "give_greeting")Actually, it there is another step, where it maps the URL to an endpoint:
URL (http://www.example.org/greeting/Mark) should be handled by Endpoint "give_greeting". Requests to Endpoint "give_greeting" should be handled by View Function "give_greeting"Basically, the "endpoint" is an identifier that is used in determining what logical unit of your code should handle the request. Normally, an endpoint is just the name of a view function. However, you can actually change the endpoint, as is done in the following example.
@app.route('/greeting/<name>', endpoint='say_hello') def give_greeting(name): return 'Hello, {0}!'.format(name)Now, when Flask routes the request, the logic looks like this:
URL (http://www.example.org/greeting/Mark) should be handled by Endpoint "say_hello". Endpoint "say_hello" should be handled by View Function "give_greeting"How You Use the Endpoint
The endpoint is commonly used for the "reverse lookup". For example, in one view of your Flask application, you want to reference another view (perhaps when you are linking from one area of the site to another). Rather than hard-code the URL, you can use
url_for(). Assume the following@app.route('/') def index(): print url_for('give_greeting', name='Mark') # This will print '/greeting/Mark' @app.route('/greeting/<name>') def give_greeting(name): return 'Hello, {0}!'.format(name)This is advantageous, as now we can change the URLs of our application without needing to change the line where we reference that resource.
Why not just always use the name of the view function?
One question that might come up is the following: "Why do we need this extra layer?" Why map a path to an endpoint, then an endpoint to a view function? Why not just skip that middle step?
The reason is because it is more powerful this way. For example, Flask Blueprints allow you to split your application into various parts. I might have all of my admin-side resources in a blueprint called "admin", and all of my user-level resources in an endpoint called "user".
Blueprints allow you to separate these into namespaces. For example...
main.py:
Read the rest at the sourceFrom Stack Overflow: asked by Fuziang, answered by Mark Hildreth (CC BY-SA 4.0)
Get the data received in a Flask request
The docs describe the attributes available on the
requestobject (from flask import request) during a request. In most common casesrequest.datawill be empty because it's used as a fallback:request.dataContains the incoming request data as string in case it came with a mimetype Flask does not handle.request.args: the key/value pairs in the URL query stringrequest.form: the key/value pairs in the body, from a HTML post form, or JavaScript request that isn't JSON encodedrequest.files: the files in the body, which Flask keeps separate fromform. HTML forms must useenctype=multipart/form-dataor files will not be uploaded.request.values: combinedargsandform, preferringargsif keys overlaprequest.json: parsed JSON data. The request must have theapplication/jsoncontent type, or userequest.get_json(force=True)to ignore the content type.
All of these are
MultiDictinstances (except forjson). You can access values using:request.form['name']: use indexing if you know the key existsrequest.form.get('name'): usegetif the key might not existrequest.form.getlist('name'): usegetlistif the key is sent multiple times and you want a list of values.getonly returns the first value.
From Stack Overflow: asked by ddinchev, answered by Robert (CC BY-SA 4.0)
How to serve static files in Flask?
In production, configure the HTTP server (Nginx, Apache, etc.) in front of your application to serve requests to
/staticfrom the static folder. A dedicated web server is very good at serving static files efficiently, although you probably won't notice a difference compared to Flask at low volumes.Flask automatically creates a
/static/<path:filename>route that will serve anyfilenameunder thestaticfolder next to the Python module that defines your Flask app. Useurl_forto link to static files:url_for('static', filename='js/analytics.js')You can also use
send_from_directoryto serve files from a directory in your own route. This takes a base directory and a path, and ensures that the path is contained in the directory, which makes it safe to accept user-provided paths. This can be useful in cases where you want to check something before serving the file, such as if the logged in user has permission.from flask import send_from_directory @app.route('/reports/<path:path>') def send_report(path): # Using request args for path will expose you to directory traversal attacks return send_from_directory('reports', path)WARNING: Do not use
send_fileorsend_static_filewith a user-supplied path. This will expose you to directory traversal attacks.send_from_directorywas designed to safely handle user-supplied paths under a known directory, and will raise an error if the path attempts to escape the directory.If you are generating a file in memory without writing it to the filesystem, you can pass a
BytesIOobject tosend_fileto serve it like a file. You'll need to pass other arguments tosend_filein this case since it can't infer things like the file name or content type.From Stack Overflow: asked by hughdbrown, answered by atupal (CC BY-SA 4.0)
Configure Flask dev server to be visible across the network
While this is possible, you should not use the Flask dev server in production. The Flask dev server is not designed to be particularly secure, stable, or efficient. See the docs on deploying for correct solutions.
The
--hostoption toflask run, or thehostparameter toapp.run(), controls what address the development server listens to. By default it runs onlocalhost, change it toflask run --host=0.0.0.0(orapp.run(host="0.0.0.0")) to run on all your machine's IP addresses.0.0.0.0is a special value that you can't use in the browser directly, you'll need to navigate to the actual IP address of the machine on the network. You may also need to adjust your firewall to allow external access to the port.The Flask quickstart docs explain this in the "Externally Visible Server" section:
If you run the server you will notice that the server is only accessible from your own computer, not from any other in the network. This is the default because in debugging mode a user of the application can execute arbitrary Python code on your computer.
If you have the debugger disabled or trust the users on your network, you can make the server publicly available simply by adding
--host=0.0.0.0to the command line:$ flask run --host=0.0.0.0This tells your operating system to listen on all public IPs.
From Stack Overflow: asked by sa125, answered by Shawn Swaner (CC BY-SA 4.0)
Return JSON response from Flask view
A view can directly return a Python dict or list and Flask will call
jsonifyautomatically.@app.route("/summary") def summary(): d = make_summary() return dFor older Flask versions, or to return a different JSON-serializable object, import and use
jsonify.from flask import jsonify @app.route("/summary") def summary(): d = make_summary() return jsonify(d)From Stack Overflow: asked by Code Ninja, answered by codegeek (CC BY-SA 4.0)
Related topics
Where these questions come from
Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.
- Stack Overflowby its contributors, named on each answerCC BY-SA13 questions