Skip to content

Stronger typing for request.headers.get method #2128

@pcorpet

Description

@pcorpet

Since v2 and the typing stubs, the get method of the Headers data structure always returns a Optional[str]. However in some cases we can know statically that it will return a str. Indeed when a default string parameter is given, then the function always return a str.

Here's a preview of my code before v2:

auth_token = flask.request.headers.get('Authorization', '').replace('Bearer ', '')

Now that werkzeug is typed, the .replace will raise an typing error when analyzed with mypy.

error: Item "None" of "Optional[str]" has no attribute "replace"

I can fix it like this:

auth_token = typing.cast(str, flask.request.headers.get('Authorization', '')).replace('Bearer ', '')

or even like this

auth_header = flask.request.headers.get('Authorization', '')
if auth_header:
  auth_token = auth_header.replace('Bearer ', '')
else:
  auth_token = ''

But I feel like all of those patches shouldn't be required. I'll send a type fix.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions