Link to Flask static files with url_for

You have by default the static endpoint for static files. Also Flask application has the following arguments: static_url_path: can be used to specify a different path for the static files on the web. Defaults to the name of the static_folder folder. static_folder: the folder with static files that should be served at static_url_path. Defaults to … Read more

How to get POSTed JSON in Flask?

First of all, the .json attribute is a property that delegates to the request.get_json() method, which documents why you see None here. You need to set the request content type to application/json for the .json property and .get_json() method (with no arguments) to work as either will produce None otherwise. See the Flask Request documentation: … Read more

Are a WSGI server and HTTP server required to serve a Flask app?

When you “run Flask” you are actually running Werkzeug’s development WSGI server, and passing your Flask app as the WSGI callable. The development server is not intended for use in production. It is not designed to be particularly efficient, stable, or secure. It does not support all the possible features of a HTTP server. Replace … Read more

How to return a dict as a JSON response from a Flask view?

As of Flask 1.1.0 a view can directly return a Python dict and Flask will call jsonify automatically. @app.route(“/summary”) def summary(): d = make_summary() return d If your Flask version is less than 1.1.0 or to return a different JSON-serializable object, import and use jsonify. from flask import jsonify @app.route(“/summary”) def summary(): d = make_summary() … Read more

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 … Read more

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 /static from 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 … Read more

Get the data received in a Flask request

The docs describe the attributes available on the request object (from flask import request) during a request. In most common cases request.data will be empty because it’s used as a fallback: request.data Contains the incoming request data as string in case it came with a mimetype Flask does not handle. request.args: the key/value pairs in … Read more

tech