summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJacopo Farina <jacopofar@users.noreply.github.com>2018-04-09 01:31:37 +0200
committerJosé Padilla <jpadilla@webapplicate.com>2018-04-08 19:31:37 -0400
commitaed7305680b0ca6cf9846cd755b420f4dfccee22 (patch)
tree430637d288fb5ca7d0333d8dd0d60d2dc603ad34
parentee2ab9fbd78f884629833feedffdc69a9d580b89 (diff)
downloadpyjwt-aed7305680b0ca6cf9846cd755b420f4dfccee22.tar.gz
RFC: Add type hints (#344)
* Add mypy to Travis and a simple type hint to _get_default_options * Make flake8 accept unused import required by mypy * Add typing to encode and decode, create encode_bytes in JWS to differentiate from encode in JWT * Use Union type to describe both types of payload
-rw-r--r--.travis.yml2
-rw-r--r--jwt/api_jws.py23
-rw-r--r--jwt/api_jwt.py28
-rw-r--r--tox.ini2
4 files changed, 44 insertions, 11 deletions
diff --git a/.travis.yml b/.travis.yml
index 6f819af..7bd5be9 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -25,7 +25,9 @@ env:
install:
- pip install -U pip
- pip install -U tox coveralls
+ - pip install -U mypy
script:
- tox
+ - mypy --ignore-missing-imports jwt
after_success:
- coveralls
diff --git a/jwt/api_jws.py b/jwt/api_jws.py
index b796fa7..3e429a7 100644
--- a/jwt/api_jws.py
+++ b/jwt/api_jws.py
@@ -2,6 +2,11 @@ import binascii
import json
import warnings
from collections import Mapping
+try:
+ # import required by mypy to perform type checking, not used for normal execution
+ from typing import Callable, Dict, List, Optional, Union # NOQA
+except ImportError:
+ pass
from .algorithms import (
Algorithm, get_default_algorithms, has_crypto, requires_cryptography # NOQA
@@ -69,8 +74,13 @@ class PyJWS(object):
"""
return list(self._valid_algs)
- def encode(self, payload, key, algorithm='HS256', headers=None,
- json_encoder=None):
+ def encode(self,
+ payload, # type: Union[Dict, bytes]
+ key, # type: str
+ algorithm='HS256', # type: str
+ headers=None, # type: Optional[Dict]
+ json_encoder=None # type: Optional[Callable]
+ ):
segments = []
if algorithm is None:
@@ -117,7 +127,12 @@ class PyJWS(object):
return b'.'.join(segments)
- def decode(self, jws, key='', verify=True, algorithms=None, options=None,
+ def decode(self,
+ token, # type: str
+ key='', # type: str
+ verify=True, # type: bool
+ algorithms=None, # type: List[str]
+ options=None, # type: Dict
**kwargs):
merged_options = merge_dict(self.options, options)
@@ -131,7 +146,7 @@ class PyJWS(object):
DeprecationWarning
)
- payload, signing_input, header, signature = self._load(jws)
+ payload, signing_input, header, signature = self._load(token)
if not verify:
warnings.warn('The verify parameter is deprecated. '
diff --git a/jwt/api_jwt.py b/jwt/api_jwt.py
index ce1e197..90fa0a1 100644
--- a/jwt/api_jwt.py
+++ b/jwt/api_jwt.py
@@ -3,6 +3,11 @@ import warnings
from calendar import timegm
from collections import Iterable, Mapping
from datetime import datetime, timedelta
+try:
+ # import required by mypy to perform type checking, not used for normal execution
+ from typing import Callable, Dict, List, Optional, Union # NOQA
+except ImportError:
+ pass
from .api_jws import PyJWS
from .algorithms import Algorithm, get_default_algorithms # NOQA
@@ -20,6 +25,7 @@ class PyJWT(PyJWS):
@staticmethod
def _get_default_options():
+ # type: () -> Dict[str, bool]
return {
'verify_signature': True,
'verify_exp': True,
@@ -32,8 +38,13 @@ class PyJWT(PyJWS):
'require_nbf': False
}
- def encode(self, payload, key, algorithm='HS256', headers=None,
- json_encoder=None):
+ def encode(self,
+ payload, # type: Union[Dict, bytes]
+ key, # type: str
+ algorithm='HS256', # type: str
+ headers=None, # type: Optional[Dict]
+ json_encoder=None # type: Optional[Callable]
+ ):
# Check that we get a mapping
if not isinstance(payload, Mapping):
raise TypeError('Expecting a mapping object, as JWT only supports '
@@ -43,7 +54,7 @@ class PyJWT(PyJWS):
for time_claim in ['exp', 'iat', 'nbf']:
# Convert datetime to a intDate value in known time-format claims
if isinstance(payload.get(time_claim), datetime):
- payload[time_claim] = timegm(payload[time_claim].utctimetuple())
+ payload[time_claim] = timegm(payload[time_claim].utctimetuple()) # type: ignore
json_payload = json.dumps(
payload,
@@ -55,7 +66,12 @@ class PyJWT(PyJWS):
json_payload, key, algorithm, headers, json_encoder
)
- def decode(self, jwt, key='', verify=True, algorithms=None, options=None,
+ def decode(self,
+ token, # type: str
+ key='', # type: str
+ verify=True, # type: bool
+ algorithms=None, # type: List[str]
+ options=None, # type: Dict
**kwargs):
if verify and not algorithms:
@@ -66,7 +82,7 @@ class PyJWT(PyJWS):
DeprecationWarning
)
- payload, signing_input, header, signature = self._load(jwt)
+ payload, _, _, _ = self._load(token)
if options is None:
options = {'verify_signature': verify}
@@ -74,7 +90,7 @@ class PyJWT(PyJWS):
options.setdefault('verify_signature', verify)
decoded = super(PyJWT, self).decode(
- jwt, key=key, algorithms=algorithms, options=options, **kwargs
+ token, key=key, algorithms=algorithms, options=options, **kwargs
)
try:
diff --git a/tox.ini b/tox.ini
index 2262348..12a162b 100644
--- a/tox.ini
+++ b/tox.ini
@@ -15,4 +15,4 @@ commands =
deps =
flake8
flake8-import-order
- pep8-naming
+ pep8-naming \ No newline at end of file