Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
72e0c29
refactor(examples): add type hints to request ID middleware recipe
ericareg Oct 21, 2026
98dc02d
refactor(examples): add type hints to request ID context recipe
ericareg Oct 21, 2026
775f302
refactor(examples): add type hints to structlog request ID recipe
ericareg Oct 21, 2026
1b4a289
refactor(examples): add type hints to header name case middleware recipe
ericareg Oct 21, 2026
ebda7f2
refactor(examples): add type hints to CSV text output recipes
ericareg Oct 21, 2026
8d66558
refactor(examples): add type hints to raw URL path recipes
ericareg Oct 21, 2026
3e39cdf
style(examples): fix import order in request ID middleware recipe
ericareg Oct 21, 2026
6c9801c
refactor(examples): add type hints to multipart mixed recipe
ericareg Oct 21, 2026
aeac383
refactor(examples): add type hints to CSV streaming recipes
ericareg Oct 21, 2026
db998f8
refactor(examples): add type hints to pretty JSON recipe
ericareg Oct 21, 2026
45b9ed2
Merge branch 'master' into type-hints-recipes
vytas7 Oct 24, 2026
b9268ad
Merge branch 'master' into type-hints-recipes
vytas7 Nov 8, 2026
42b8e44
chore(examples): type-check recipes with mypy and drop __future__ imp…
ericareg Nov 9, 2026
6ad125d
Merge branch 'master' into type-hints-recipes
vytas7 Nov 11, 2026
e7941d5
Merge branch 'master' into type-hints-recipes
vytas7 Nov 11, 2026
b188720
chore(examples): address review feedback on recipe type hints
ericareg Nov 16, 2026
d91e229
test(recipes): skip PEP 604 annotated recipe tests on Python < 3.10
ericareg Nov 18, 2026
8e64c1b
Merge branch 'master' into type-hints-recipes
vytas7 Nov 20, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion examples/recipes/header_name_case_mw.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,6 @@ def start_response_wrapper(status, response_headers, exc_info=None):
(self._capitalization.get(name, name), value)
for name, value in response_headers
]
start_response(status, headers, exc_info)
return start_response(status, headers, exc_info)
Comment thread
vytas7 marked this conversation as resolved.
Resolved

return self._app(environ, start_response_wrapper)
4 changes: 3 additions & 1 deletion examples/recipes/msgspec_media_validation.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Any

import msgspec

from falcon import Request
Expand All @@ -6,7 +8,7 @@

class MsgspecMiddleware:
def process_resource(
self, req: Request, resp: Response, resource: object, params: dict
self, req: Request, resp: Response, resource: object, params: dict[str, Any]
) -> None:
if schema := getattr(resource, f'{req.method}_SCHEMA', None):
param = schema.__name__.lower()
Expand Down
6 changes: 2 additions & 4 deletions examples/recipes/msgspec_msgpack_handler.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from typing import Optional

from msgspec import msgpack

from falcon import media
Expand All @@ -10,8 +8,8 @@ class MsgspecMessagePackHandler(media.BaseHandler):
def deserialize(
self,
stream: ReadableIO,
content_type: Optional[str],
content_length: Optional[int],
content_type: str | None,
content_length: int | None,
) -> object:
return msgpack.decode(stream.read())

Expand Down
2 changes: 1 addition & 1 deletion examples/recipes/multipart_mixed_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@


class Forms:
def on_post(self, req, resp):
def on_post(self, req: falcon.Request, resp: falcon.Response) -> None:
example = {}
for part in req.media:
if part.content_type.startswith('multipart/mixed'):
Expand Down
16 changes: 10 additions & 6 deletions examples/recipes/output_csv_stream_asgi.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
from collections.abc import AsyncIterator
import csv

import falcon
import falcon.asgi


class Report:
class PseudoTextStream:
def __init__(self):
def __init__(self) -> None:
self.clear()

def clear(self):
self.result = []
def clear(self) -> None:
self.result: list[bytes] = []

def write(self, data):
def write(self, data: str) -> None:
self.result.append(data.encode())

async def fibonacci_generator(self, n=1000):
async def fibonacci_generator(self, n: int = 1000) -> AsyncIterator[bytes]:
stream = self.PseudoTextStream()
writer = csv.writer(stream, quoting=csv.QUOTE_NONNUMERIC)
writer.writerow(('n', 'Fibonacci Fn'))
Expand All @@ -29,7 +31,9 @@ async def fibonacci_generator(self, n=1000):
yield chunk
stream.clear()

async def on_get(self, req, resp):
async def on_get(
self, req: falcon.asgi.Request, resp: falcon.asgi.Response
) -> None:
resp.content_type = falcon.MEDIA_CSV
resp.downloadable_as = 'report.csv'
resp.stream = self.fibonacci_generator()
13 changes: 7 additions & 6 deletions examples/recipes/output_csv_stream_wsgi.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
from collections.abc import Iterator
import csv

import falcon


class Report:
class PseudoTextStream:
def __init__(self):
def __init__(self) -> None:
self.clear()

def clear(self):
self.result = []
def clear(self) -> None:
self.result: list[bytes] = []

def write(self, data):
def write(self, data: str) -> None:
self.result.append(data.encode())

def fibonacci_generator(self, n=1000):
def fibonacci_generator(self, n: int = 1000) -> Iterator[bytes]:
stream = self.PseudoTextStream()
writer = csv.writer(stream, quoting=csv.QUOTE_NONNUMERIC)
writer.writerow(('n', 'Fibonacci Fn'))
Expand All @@ -28,7 +29,7 @@ def fibonacci_generator(self, n=1000):
yield from stream.result
stream.clear()

def on_get(self, req, resp):
def on_get(self, req: falcon.Request, resp: falcon.Response) -> None:
resp.content_type = falcon.MEDIA_CSV
resp.downloadable_as = 'report.csv'
resp.stream = self.fibonacci_generator()
5 changes: 4 additions & 1 deletion examples/recipes/output_csv_text_asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@
import io

import falcon
import falcon.asgi


class Report:
async def on_get(self, req, resp):
async def on_get(
self, req: falcon.asgi.Request, resp: falcon.asgi.Response
) -> None:
output = io.StringIO()
writer = csv.writer(output, quoting=csv.QUOTE_NONNUMERIC)
writer.writerow(('fruit', 'quantity'))
Expand Down
2 changes: 1 addition & 1 deletion examples/recipes/output_csv_text_wsgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@


class Report:
def on_get(self, req, resp):
def on_get(self, req: falcon.Request, resp: falcon.Response) -> None:
output = io.StringIO()
writer = csv.writer(output, quoting=csv.QUOTE_NONNUMERIC)
writer.writerow(('fruit', 'quantity'))
Expand Down
17 changes: 12 additions & 5 deletions examples/recipes/pretty_json_main.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,28 @@
import json

import falcon
from falcon.typing import ReadableIO


class CustomJSONHandler(falcon.media.BaseHandler):
MAX_INDENT_LEVEL = 8

def deserialize(self, stream, content_type, content_length):
def deserialize(
self,
stream: ReadableIO,
content_type: str | None,
content_length: int | None,
) -> object:
data = stream.read()
return json.loads(data.decode())

def serialize(self, media, content_type):
def serialize(self, media: object, content_type: str) -> bytes:
_, params = falcon.parse_header(content_type)
indent = params.get('indent')
if indent is not None:
indent_param = params.get('indent')
indent: int | None = None
if indent_param is not None:
try:
indent = int(indent)
indent = int(indent_param)
# NOTE: Impose a reasonable indentation level limit.
if indent < 0 or indent > self.MAX_INDENT_LEVEL:
indent = None
Expand Down
12 changes: 9 additions & 3 deletions examples/recipes/raw_url_path_asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@


class RawPathComponent:
async def process_request(self, req, resp):
async def process_request(
self, req: falcon.asgi.Request, resp: falcon.asgi.Response
) -> None:
raw_path = req.scope.get('raw_path')

# NOTE: Decode the raw path from the raw_path bytestring, disallowing
Expand All @@ -13,13 +15,17 @@ async def process_request(self, req, resp):


class URLResource:
async def on_get(self, req, resp, url):
async def on_get(
self, req: falcon.asgi.Request, resp: falcon.asgi.Response, url: str
) -> None:
# NOTE: url here is potentially percent-encoded.
url = falcon.uri.decode(url)

resp.media = {'url': url}

async def on_get_status(self, req, resp, url):
async def on_get_status(
self, req: falcon.asgi.Request, resp: falcon.asgi.Response, url: str
) -> None:
# NOTE: url here is potentially percent-encoded.
url = falcon.uri.decode(url)

Expand Down
8 changes: 5 additions & 3 deletions examples/recipes/raw_url_path_wsgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@


class RawPathComponent:
def process_request(self, req, resp):
def process_request(self, req: falcon.Request, resp: falcon.Response) -> None:
raw_uri = req.env.get('RAW_URI') or req.env.get('REQUEST_URI')

# NOTE: Reconstruct the percent-encoded path from the raw URI.
Expand All @@ -12,13 +12,15 @@ def process_request(self, req, resp):


class URLResource:
def on_get(self, req, resp, url):
def on_get(self, req: falcon.Request, resp: falcon.Response, url: str) -> None:
# NOTE: url here is potentially percent-encoded.
url = falcon.uri.decode(url)

resp.media = {'url': url}

def on_get_status(self, req, resp, url):
def on_get_status(
self, req: falcon.Request, resp: falcon.Response, url: str
) -> None:
# NOTE: url here is potentially percent-encoded.
url = falcon.uri.decode(url)

Expand Down
10 changes: 6 additions & 4 deletions examples/recipes/request_id_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,17 @@


class _Context:
def __init__(self):
self._request_id_var = contextvars.ContextVar('request_id', default=None)
def __init__(self) -> None:
self._request_id_var: contextvars.ContextVar[str | None] = (
contextvars.ContextVar('request_id', default=None)
)

@property
def request_id(self):
def request_id(self) -> str | None:
return self._request_id_var.get()

@request_id.setter
def request_id(self, value):
def request_id(self, value: str | None) -> None:
self._request_id_var.set(value)


Expand Down
2 changes: 1 addition & 1 deletion examples/recipes/request_id_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from my_app.context import ctx


def create_widget_object(name: str):
def create_widget_object(name: str) -> None:
request_id = f'request_id={ctx.request_id}'
logging.debug('%s going to create widget: %s', request_id, name)

Expand Down
12 changes: 10 additions & 2 deletions examples/recipes/request_id_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,20 @@
# Import the above context.py
from my_app.context import ctx

import falcon


class RequestIDMiddleware:
def process_request(self, req, resp):
def process_request(self, req: falcon.Request, resp: falcon.Response) -> None:
request_id = str(uuid4())
ctx.request_id = request_id

# It may also be helpful to include the ID in the response
def process_response(self, req, resp, resource, req_succeeded):
def process_response(
self,
req: falcon.Request,
resp: falcon.Response,
resource: object,
req_succeeded: bool,
) -> None:
resp.set_header('X-Request-ID', ctx.request_id)
12 changes: 10 additions & 2 deletions examples/recipes/request_id_structlog.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
# Optional logging package (pip install structlog)
import structlog

import falcon


class RequestIDMiddleware:
def process_request(self, req, resp):
def process_request(self, req: falcon.Request, resp: falcon.Response) -> None:
request_id = str(uuid4())

# Using Falcon 2.0+ context style
Expand All @@ -15,5 +17,11 @@ def process_request(self, req, resp):
req.context.log = structlog.get_logger(request_id=request_id)

# It may also be helpful to include the ID in the response
def process_response(self, req, resp, resource, req_succeeded):
def process_response(
self,
req: falcon.Request,
resp: falcon.Response,
resource: object,
req_succeeded: bool,
) -> None:
resp.set_header('X-Request-ID', req.context.request_id)
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,9 @@ module = [
"meinheld",
"msgpack",
"mujson",
"my_app.*",
"pyximport",
"structlog",
"testtools",
"uvicorn"
]
Expand Down
10 changes: 10 additions & 0 deletions tests/test_recipes.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import sys
import types
import unittest.mock

Expand Down Expand Up @@ -80,6 +81,9 @@ def test_csv_output(self, asgi, app_kind, util, recipe, expected_head):
assert result.text.startswith(expected_head)


@pytest.mark.skipif(
sys.version_info < (3, 10), reason='this recipe uses PEP 604 annotations'
)
class TestPrettyJSON:
class QuoteResource:
def on_get(self, req, resp):
Expand Down Expand Up @@ -164,6 +168,9 @@ def test_text_plain_basic(self, util):
assert response.text == payload


@pytest.mark.skipif(
sys.version_info < (3, 10), reason='this recipe uses PEP 604 annotations'
)
class TestRequestIDContext:
@pytest.fixture(params=['middleware', 'structlog'])
def app(self, request, util, register_module):
Expand Down Expand Up @@ -212,6 +219,9 @@ def test_request_id_header(self, app):
assert response.headers['X-Request-ID'] == response.json['request_id']


@pytest.mark.skipif(
sys.version_info < (3, 10), reason='this recipe uses PEP 604 annotations'
)
class TestMsgspec:
@pytest.fixture(autouse=True)
# TODO(vytas): Make this @classmethod when we drop CPython 3.9 support.
Expand Down
4 changes: 4 additions & 0 deletions tox.toml
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,10 @@ commands = [
["mypy", "--strict", "e2e-tests/server"],
["mypy", "--strict", "tests/test_typing.py"],
["mypy", "tests", "--allow-untyped-calls", "--allow-untyped-defs", "--no-check-untyped-defs"],
# header_name_case_app.py intentionally contains a placeholder for
# CustomHeadersMiddleware (see the recipe's docs), whereas
# header_name_case_mw.py and plain_text_main.py are deliberately untyped.
["mypy", "examples/recipes", "--exclude", "(header_name_case_app|header_name_case_mw|plain_text_main)\\.py"],
]

[env.pyright_tests]
Expand Down
Loading