Flask provides several helper functions to simplify common web development tasks.
URL Generation
url_for
url_for(
endpoint: str,
*,
_anchor: str | None = None,
_method: str | None = None,
_scheme: str | None = None,
_external: bool | None = None,
**values: Any
) -> str
Generate a URL to the given endpoint with the given values.
This requires an active request or application context, and calls current_app.url_for().
The endpoint name associated with the URL to generate. If this starts with a ., the current blueprint name (if any) will be used.
If given, append this as #anchor to the URL.
If given, generate the URL associated with this method for the endpoint.
If given, the URL will have this scheme if it is external.
If given, prefer the URL to be internal (False) or require it to be external (True). External URLs include the scheme and domain. When not in an active request, URLs are external by default.
Values to use for the variable parts of the URL rule. Unknown keys are appended as query string arguments, like ?a=b&c=d.
Example
from flask import url_for
@app.route('/user/<username>')
def profile(username):
return f'User: {username}'
# Generate URL for the profile endpoint
url = url_for('profile', username='john')
# Result: '/user/john'
# Generate URL with query parameters
url = url_for('profile', username='john', page=2)
# Result: '/user/john?page=2'
# Generate external URL
url = url_for('profile', username='john', _external=True)
# Result: 'http://example.com/user/john'
# Generate URL with anchor
url = url_for('profile', username='john', _anchor='bio')
# Result: '/user/john#bio'
Response Helpers
make_response
make_response(*args: Any) -> Response
Create a response object that you can use to attach headers or modify the response before returning.
Parameters
Arguments that would normally be returned from a view. Can be:
- No arguments: creates an empty response
- One argument: passed to
Flask.make_response
- Multiple arguments: passed as a tuple to
Flask.make_response
Example
from flask import make_response, render_template
@app.route('/')
def index():
response = make_response(render_template('index.html', foo=42))
response.headers['X-Custom-Header'] = 'custom value'
return response
# With status code
@app.route('/not-found')
def not_found():
return make_response(render_template('404.html'), 404)
redirect
redirect(
location: str,
code: int = 303,
Response: type[BaseResponse] | None = None
) -> BaseResponse
Create a redirect response object.
The status code for the redirect.
Response
type[BaseResponse] | None
The response class to use. Not used when current_app is active, which uses app.response_class.
Example
from flask import redirect, url_for
@app.route('/old-page')
def old_page():
return redirect(url_for('new_page'))
@app.route('/login')
def login():
# Redirect to external URL
return redirect('https://example.com/auth')
# With custom status code
@app.route('/moved')
def moved():
return redirect(url_for('new_location'), code=301)
abort
abort(
code: int | BaseResponse,
*args: Any,
**kwargs: Any
) -> NoReturn
Raise an HTTPException for the given status code.
code
int | BaseResponse
required
The status code for the exception, which must be registered in app.aborter.
Example
from flask import abort
@app.route('/user/<int:user_id>')
def get_user(user_id):
user = User.query.get(user_id)
if user is None:
abort(404)
return user.to_dict()
@app.route('/admin')
def admin():
if not current_user.is_admin:
abort(403, description="Admin access required")
return render_template('admin.html')
Flash Messages
flash
flash(message: str, category: str = "message") -> None
Flash a message to the next request. The template must call get_flashed_messages() to display it.
The message to be flashed.
The category for the message. Recommended values:
'message' for any kind of message
'error' for errors
'info' for information messages
'warning' for warnings
Any string can be used as a category.
Example
from flask import flash, redirect, url_for
@app.route('/save', methods=['POST'])
def save():
# Process form data
flash('Your changes have been saved.', 'success')
return redirect(url_for('index'))
@app.route('/delete/<int:id>', methods=['POST'])
def delete(id):
try:
delete_item(id)
flash('Item deleted successfully.', 'success')
except Exception as e:
flash(f'Error deleting item: {e}', 'error')
return redirect(url_for('list'))
get_flashed_messages
get_flashed_messages(
with_categories: bool = False,
category_filter: Iterable[str] = ()
) -> list[str] | list[tuple[str, str]]
Pull all flashed messages from the session and return them. Further calls in the same request return the same messages.
Set to True to return tuples in the form (category, message) instead of just messages.
category_filter
Iterable[str]
default:"()"
Filter the flashed messages to one or more categories. Only categories in the list will be returned.
Example
# In your template
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class="flashes">
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
# With categories
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<div class="alert alert-{{ category }}">
{{ message }}
</div>
{% endfor %}
{% endif %}
{% endwith %}
# Filter by category
{% with errors = get_flashed_messages(category_filter=['error']) %}
{% if errors %}
<div class="errors">
{% for error in errors %}
<p>{{ error }}</p>
{% endfor %}
</div>
{% endif %}
{% endwith %}
File Sending
send_file
send_file(
path_or_file: os.PathLike | str | IO[bytes],
mimetype: str | None = None,
as_attachment: bool = False,
download_name: str | None = None,
conditional: bool = True,
etag: bool | str = True,
last_modified: datetime | int | float | None = None,
max_age: int | Callable[[str | None], int | None] | None = None
) -> Response
Send the contents of a file to the client.
Never pass file paths provided by a user. The path is assumed to be trusted. Use send_from_directory to safely serve user-requested paths.
path_or_file
os.PathLike | str | IO[bytes]
required
The path to the file to send, or a file-like object opened in binary mode.
The MIME type to send for the file. If not provided, it will be detected from the file name.
Indicate to a browser that it should offer to save the file instead of displaying it.
The default name browsers will use when saving the file. Defaults to the passed file name.
Enable conditional and range responses based on request headers.
Calculate an ETag for the file. Can also be a string to use instead.
last_modified
datetime | int | float | None
The last modified time to send for the file, in seconds. If not provided, it will be detected from the file path.
How long the client should cache the file, in seconds. If set, Cache-Control will be public, otherwise it will be no-cache.
Example
from flask import send_file
import io
@app.route('/report.pdf')
def download_report():
return send_file(
'reports/monthly.pdf',
mimetype='application/pdf',
as_attachment=True,
download_name='report.pdf'
)
# Send from memory
@app.route('/generate-csv')
def generate_csv():
data = generate_csv_data()
buffer = io.BytesIO(data.encode())
return send_file(
buffer,
mimetype='text/csv',
as_attachment=True,
download_name='data.csv'
)
send_from_directory
send_from_directory(
directory: os.PathLike[str] | str,
path: os.PathLike[str] | str,
**kwargs: Any
) -> Response
Send a file from within a directory using send_file. This is a secure way to serve files from a folder.
directory
os.PathLike[str] | str
required
The directory that path must be located under. This must not be a value provided by the client.
path
os.PathLike[str] | str
required
The path to the file to send, relative to directory.
Arguments to pass to send_file.
Example
from flask import send_from_directory
@app.route('/uploads/<path:name>')
def download_file(name):
return send_from_directory(
app.config['UPLOAD_FOLDER'],
name,
as_attachment=True
)
# Serve user avatars
@app.route('/avatar/<username>')
def get_avatar(username):
return send_from_directory(
'static/avatars',
f'{username}.jpg',
mimetype='image/jpeg'
)
Streaming
stream_with_context
stream_with_context(
generator_or_function: Iterator[AnyStr] | Callable[..., Iterator[AnyStr]]
) -> Iterator[AnyStr] | Callable
Wrap a response generator function so that it runs inside the current request context. This keeps request, session, and g available during streaming.
More headers cannot be sent after the body has begun. Make sure all headers are set before starting the response. Do not modify the session in the generator, as the Set-Cookie header will already be sent.
Example
from flask import stream_with_context, request, Response
# Use as a decorator
@app.get("/stream")
def streamed_response():
@stream_with_context
def generate():
yield "Hello "
yield request.args["name"]
yield "!"
return Response(generate())
# Use as a wrapper
@app.get("/stream")
def streamed_response():
def generate():
yield "Hello "
yield request.args["name"]
yield "!"
return Response(stream_with_context(generate()))
Template Helpers
get_template_attribute
get_template_attribute(template_name: str, attribute: str) -> Any
Load a macro (or variable) that a template exports. This can be used to invoke a macro from within Python code.
The name of the template.
The name of the variable or macro to access.
Example
from flask import get_template_attribute
# In _macros.html:
# {% macro hello(name) %}Hello {{ name }}!{% endmacro %}
# In Python code:
hello = get_template_attribute('_macros.html', 'hello')
greeting = hello('World')
# Result: 'Hello World!'
Environment Helpers
get_debug_flag
Get whether debug mode should be enabled for the app, indicated by the FLASK_DEBUG environment variable. The default is False.
Example
from flask.helpers import get_debug_flag
if get_debug_flag():
app.config['TESTING'] = True
get_load_dotenv
get_load_dotenv(default: bool = True) -> bool
Get whether the user has disabled loading default dotenv files by setting FLASK_SKIP_DOTENV. The default is True (load the files).
What to return if the env var isn’t set.
Example
from flask.helpers import get_load_dotenv
if get_load_dotenv():
# Load environment variables from .env file
pass