14
14
import time
15
15
import weakref
16
16
from collections import namedtuple
17
- from collections .abc import Mapping
17
+ from collections .abc import Mapping as ABCMapping
18
18
from contextlib import suppress
19
19
from math import ceil
20
20
from pathlib import Path
21
+ from typing import Any , Dict , List , Optional , Tuple # noqa
21
22
from urllib .parse import quote
22
23
from urllib .request import getproxies
23
24
41
42
idna_ssl .patch_match_hostname ()
42
43
43
44
44
- sentinel = object ()
45
- NO_EXTENSIONS = bool (os .environ .get ('AIOHTTP_NO_EXTENSIONS' ))
45
+ sentinel = object () # type: Any
46
+ NO_EXTENSIONS = bool (os .environ .get ('AIOHTTP_NO_EXTENSIONS' )) # type: bool
46
47
47
48
# N.B. sys.flags.dev_mode is available on Python 3.7+, use getattr
48
49
# for compatibility with older versions
59
60
60
61
61
62
coroutines = asyncio .coroutines
62
- old_debug = coroutines ._DEBUG
63
+ old_debug = coroutines ._DEBUG # type: ignore
63
64
64
65
# prevent "coroutine noop was never awaited" warning.
65
- coroutines ._DEBUG = False
66
+ coroutines ._DEBUG = False # type: ignore
66
67
67
68
68
69
@asyncio .coroutine
69
70
def noop (* args , ** kwargs ):
70
71
return
71
72
72
73
73
- coroutines ._DEBUG = old_debug
74
+ coroutines ._DEBUG = old_debug # type: ignore
74
75
75
76
76
77
class BasicAuth (namedtuple ('BasicAuth' , ['login' , 'password' , 'encoding' ])):
77
78
"""Http basic authentication helper."""
78
79
79
- def __new__ (cls , login , password = '' , encoding = 'latin1' ):
80
+ def __new__ (cls , login : str ,
81
+ password : str = '' ,
82
+ encoding : str = 'latin1' ) -> 'BasicAuth' :
80
83
if login is None :
81
84
raise ValueError ('None is not allowed as login value' )
82
85
@@ -90,7 +93,7 @@ def __new__(cls, login, password='', encoding='latin1'):
90
93
return super ().__new__ (cls , login , password , encoding )
91
94
92
95
@classmethod
93
- def decode (cls , auth_header , encoding = 'latin1' ):
96
+ def decode (cls , auth_header : str , encoding : str = 'latin1' ) -> 'BasicAuth' :
94
97
"""Create a BasicAuth object from an Authorization HTTP header."""
95
98
split = auth_header .strip ().split (' ' )
96
99
if len (split ) == 2 :
@@ -110,21 +113,22 @@ def decode(cls, auth_header, encoding='latin1'):
110
113
return cls (username , password , encoding = encoding )
111
114
112
115
@classmethod
113
- def from_url (cls , url , * , encoding = 'latin1' ):
116
+ def from_url (cls , url : URL ,
117
+ * , encoding : str = 'latin1' ) -> Optional ['BasicAuth' ]:
114
118
"""Create BasicAuth from url."""
115
119
if not isinstance (url , URL ):
116
120
raise TypeError ("url should be yarl.URL instance" )
117
121
if url .user is None :
118
122
return None
119
123
return cls (url .user , url .password or '' , encoding = encoding )
120
124
121
- def encode (self ):
125
+ def encode (self ) -> str :
122
126
"""Encode credentials."""
123
127
creds = ('%s:%s' % (self .login , self .password )).encode (self .encoding )
124
128
return 'Basic %s' % base64 .b64encode (creds ).decode (self .encoding )
125
129
126
130
127
- def strip_auth_from_url (url ) :
131
+ def strip_auth_from_url (url : URL ) -> Tuple [ URL , Optional [ BasicAuth ]] :
128
132
auth = BasicAuth .from_url (url )
129
133
if auth is None :
130
134
return url , None
@@ -293,6 +297,9 @@ def content_disposition_header(disptype, quote_fields=True, **params):
293
297
return value
294
298
295
299
300
+ KeyMethod = namedtuple ('KeyMethod' , 'key method' )
301
+
302
+
296
303
class AccessLogger (AbstractAccessLogger ):
297
304
"""Helper object to log access.
298
305
@@ -336,9 +343,7 @@ class AccessLogger(AbstractAccessLogger):
336
343
LOG_FORMAT = '%a %t "%r" %s %b "%{Referer}i" "%{User-Agent}i"'
337
344
FORMAT_RE = re .compile (r'%(\{([A-Za-z0-9\-_]+)\}([ioe])|[atPrsbOD]|Tf?)' )
338
345
CLEANUP_RE = re .compile (r'(%[^s])' )
339
- _FORMAT_CACHE = {}
340
-
341
- KeyMethod = namedtuple ('KeyMethod' , 'key method' )
346
+ _FORMAT_CACHE = {} # type: Dict[str, Tuple[str, List[KeyMethod]]]
342
347
343
348
def __init__ (self , logger , log_format = LOG_FORMAT ):
344
349
"""Initialise the logger.
@@ -390,7 +395,7 @@ def compile_format(self, log_format):
390
395
m = getattr (AccessLogger , '_format_%s' % atom [2 ])
391
396
m = functools .partial (m , atom [1 ])
392
397
393
- methods .append (self . KeyMethod (format_key , m ))
398
+ methods .append (KeyMethod (format_key , m ))
394
399
395
400
log_format = self .FORMAT_RE .sub (r'%s' , log_format )
396
401
log_format = self .CLEANUP_RE .sub (r'%\1' , log_format )
@@ -515,7 +520,7 @@ def __set__(self, inst, value):
515
520
try :
516
521
from ._helpers import reify as reify_c
517
522
if not NO_EXTENSIONS :
518
- reify = reify_c
523
+ reify = reify_c # type: ignore
519
524
except ImportError :
520
525
pass
521
526
@@ -716,25 +721,25 @@ def _parse_content_type(self, raw):
716
721
self ._content_type , self ._content_dict = cgi .parse_header (raw )
717
722
718
723
@property
719
- def content_type (self , * , _CONTENT_TYPE = hdrs . CONTENT_TYPE ):
724
+ def content_type (self ):
720
725
"""The value of content part for Content-Type HTTP header."""
721
- raw = self ._headers .get (_CONTENT_TYPE )
726
+ raw = self ._headers .get (hdrs . CONTENT_TYPE )
722
727
if self ._stored_content_type != raw :
723
728
self ._parse_content_type (raw )
724
729
return self ._content_type
725
730
726
731
@property
727
- def charset (self , * , _CONTENT_TYPE = hdrs . CONTENT_TYPE ):
732
+ def charset (self ):
728
733
"""The value of charset part for Content-Type HTTP header."""
729
- raw = self ._headers .get (_CONTENT_TYPE )
734
+ raw = self ._headers .get (hdrs . CONTENT_TYPE )
730
735
if self ._stored_content_type != raw :
731
736
self ._parse_content_type (raw )
732
737
return self ._content_dict .get ('charset' )
733
738
734
739
@property
735
- def content_length (self , * , _CONTENT_LENGTH = hdrs . CONTENT_LENGTH ):
740
+ def content_length (self ):
736
741
"""The value of Content-Length HTTP header."""
737
- content_length = self ._headers .get (_CONTENT_LENGTH )
742
+ content_length = self ._headers .get (hdrs . CONTENT_LENGTH )
738
743
739
744
if content_length :
740
745
return int (content_length )
@@ -750,7 +755,7 @@ def set_exception(fut, exc):
750
755
fut .set_exception (exc )
751
756
752
757
753
- class ChainMapProxy (Mapping ):
758
+ class ChainMapProxy (ABCMapping ):
754
759
__slots__ = ('_maps' ,)
755
760
756
761
def __init__ (self , maps ):
0 commit comments