Flask Utility Functions and Classes API

Flask provides a set of globally available functions for common operations such as generating URLs, terminating requests, and building responses.

All passedfrom flask import ...Import.


Global proxy object

Object Type Description
current_app Proxy → Flask Points to the currently active Flask application instance. Available in the application context.

URL and redirects.

Function Signature Description
url_for (endpoint, *, _anchor, _method, _scheme, _external, **values) Generate a URL based on the view function name. _external=True generates an absolute URL.
redirect (location, code=303, Response=None) Create a redirect response. The code defaults to 303 (See Other).

Request teardown and response construction.

Function Signature Description
abort (code, *args, **kwargs) Terminate the request immediately and return an HTTP error. code is the status code, description is the description.
make_response (*args) Convert the view return value into a Response object. When multiple arguments are passed, treat them as a tuple.
after_this_request (func) Registers a function to be executed only once after the current request. Used to dynamically add after_request.

Context check

Function Description
has_request_context() Return True if there is an active request context.
has_app_context() Return True if there is an active application context.
copy_current_request_context(func) Decorator. Copies the current request context so that the decorated function can still access request, g, etc. when running outside the context.

File sending

Function Signature Description
send_file (path_or_file, mimetype, as_attachment, download_name, conditional, etag, last_modified, max_age) Send file content. as_attachment=True triggers a download. Supports conditional requests and ETag.
send_from_directory (directory, path, **kwargs) Safely sends files from a specified directory. Uses safe_join to prevent path traversal attacks.

Code Examples

Example

from flask import (Flask, current_app, url_for, redirect,
                   abort, make_response, after_this_request,
                   has_request_context, send_file, send_from_directory)

app = Flask(__name__)

@app.route("/")
def index():
    # url_for generates URL
    login_url = url_for("login")
    # Generate absolute URL (including domain name)
    full_url = url_for("profile", username="example", _external=True)
    return f'<a href="{login_url}">Login</a>'

@app.route("/redirect-me")
def redirect_me():
    # Redirect to homepage
    return redirect(url_for("index"))

@app.route("/profile/<username>")
def profile(username):
    return f"Profile: {username}"

@app.route("/admin")
def admin():
    # Unauthorized access, returns 403
    abort(403, description="Access denied")

@app.route("/download")
def download():
    # Send file (trigger browser download)
    return send_from_directory("uploads", "report.pdf",
                               as_attachment=True,
                               download_name="example_report.pdf")

@app.route("/custom-response")
def custom_response():
    # Manually construct response object
    resp = make_response("<h1>Custom</h1>")
    resp.headers["X-Powered-By"] = "EXAMPLE"

    @after_this_request
    def log_response(response):
        app.logger.info(f"Request to {request.path} done, status={response.status_code}")
        return response

    return resp
other extensions