flask.app Headers Example Code

Headers is class within the flask.app module of the Flask web framework that is imported from the datastructures module of the Werkzeug project. Headers handles the HTTP headers from requests and responses for Flask web applications.

BadRequest, Flask, and ImmutableDict are several other callables with code examples from the same flask.app package.

These topics are also useful while reading the Headers examples:

Example 1 from CTFd

CTFd (homepage) is a capture the flag (CTF) hacking web app built with Flask. The application can be used as-is to run CTF events, or modified for custom rules for related scenarios. CTFd is open sourced under the Apache License 2.0.

CTFd / tests / helpers.py

# helpers.py
import datetime
import gc
import random
import string
import uuid
from collections import namedtuple
from contextlib import contextmanager
from unittest.mock import Mock, patch

import requests
from flask.testing import FlaskClient
from freezegun import freeze_time
from sqlalchemy.engine.url import make_url
from sqlalchemy_utils import drop_database
from werkzeug.datastructures import Headers

from CTFd import create_app
from CTFd.cache import cache, clear_standings
from CTFd.config import TestingConfig
from CTFd.models import (
    Awards,
    ChallengeComments,
    ChallengeFiles,
    Challenges,
    ChallengeTopics,
    Comments,
    Fails,
    Fields,
    Files,
    Flags,
    Hints,
    Notifications,
    PageComments,
    PageFiles,
    Pages,
    Solves,
    Tags,
    TeamComments,
    Teams,
    Tokens,
    Topics,
    Tracking,
    Unlocks,
    UserComments,
    Users,
)
from CTFd.utils import set_config
from tests.constants.time import FreezeTimes

text_type = str
binary_type = bytes


FakeRequest = namedtuple("FakeRequest", ["form"])


class CTFdTestClient(FlaskClient):
    def open(self, *args, **kwargs):
        if kwargs.get("json") is not None:
            with self.session_transaction() as sess:
                api_key_headers = Headers({"CSRF-Token": sess.get("nonce")})
                headers = kwargs.pop("headers", Headers())
                if isinstance(headers, dict):
                    headers = Headers(headers)
                headers.extend(api_key_headers)
                kwargs["headers"] = headers
        return super(CTFdTestClient, self).open(*args, **kwargs)


class ctftime:
    @contextmanager
    def init():
        try:
            set_config("start", FreezeTimes.START)
            set_config("end", FreezeTimes.END)
            yield
        finally:
            set_config("start", None)
            set_config("end", None)

    @contextmanager
    def not_started():
        try:
            freezer = freeze_time(FreezeTimes.NOT_STARTED)
            frozen_time = freezer.start()
            yield frozen_time
        finally:
            freezer.stop()


## ... source file continues with no further Headers examples...

Example 2 from flask-restx

Flask RESTX is an extension that makes it easier to build RESTful APIs into your applications. Flask RESTX aims for minimal configuration to get basic APIs running for existing applications and it exposes endpoint documentation using Swagger.

Flask RESTX is provided as open source under the BSD 3-Clause license.

flask-restx / flask_restx / api.py

# api.py
import difflib
import inspect
from itertools import chain
import logging
import operator
import re
import six
import sys
import warnings

from collections import OrderedDict
from functools import wraps, partial
from types import MethodType

from flask import url_for, request, current_app
from flask import make_response as original_flask_make_response
try:
    from flask.helpers import _endpoint_from_view_func
except ImportError:
    from flask.scaffold import _endpoint_from_view_func
from flask.signals import got_request_exception

from jsonschema import RefResolver

from werkzeug.utils import cached_property
from werkzeug.datastructures import Headers
from werkzeug.exceptions import (
    HTTPException,
    MethodNotAllowed,
    NotFound,
    NotAcceptable,
    InternalServerError,
)

from werkzeug import __version__ as werkzeug_version

if werkzeug_version.split('.')[0] >= '2':
    from werkzeug.wrappers import Response as BaseResponse
else:
    from werkzeug.wrappers import BaseResponse

from . import apidoc
from .mask import ParseError, MaskError
from .namespace import Namespace
from .postman import PostmanCollectionV1
from .resource import Resource
from .swagger import Swagger
from .utils import default_id, camel_to_dash, unpack
from .representations import output_json
from ._http import HTTPStatus


## ... source file abbreviated to get to Headers examples ...


        if self._has_fr_route():
            try:
                return self.handle_error(e)
            except Exception as f:
                return original_handler(f)
        return original_handler(e)

    def handle_error(self, e):
        if (
            not isinstance(e, HTTPException)
            and current_app.propagate_exceptions
            and not isinstance(e, tuple(self._own_and_child_error_handlers.keys()))
        ):

            exc_type, exc_value, tb = sys.exc_info()
            if exc_value is e:
                raise
            else:
                raise e

        include_message_in_response = current_app.config.get(
            "ERROR_INCLUDE_MESSAGE", True
        )
        default_data = {}

        headers = Headers()

        for typecheck, handler in six.iteritems(self._own_and_child_error_handlers):
            if isinstance(e, typecheck):
                result = handler(e)
                default_data, code, headers = unpack(
                    result, HTTPStatus.INTERNAL_SERVER_ERROR
                )
                break
        else:
            got_request_exception.send(current_app._get_current_object(), exception=e)

            if isinstance(e, HTTPException):
                code = HTTPStatus(e.code)
                if include_message_in_response:
                    default_data = {"message": getattr(e, "description", code.phrase)}
                headers = e.get_response().headers
            elif self._default_error_handler:
                result = self._default_error_handler(e)
                default_data, code, headers = unpack(
                    result, HTTPStatus.INTERNAL_SERVER_ERROR
                )
            else:
                code = HTTPStatus.INTERNAL_SERVER_ERROR
                if include_message_in_response:


## ... source file continues with no further Headers examples...

Full Stack Python

Full Stack Python is an open book that explains concepts in plain language and provides helpful resources for those topics.
Updates via Twitter & Facebook.

Matt Makai 2012-2022