Repository navigation
Expand file tree
/
Copy pathurlopen.py
More file actions
208 lines (164 loc) · 5.8 KB
/
Copy pathurlopen.py
File metadata and controls
208 lines (164 loc) · 5.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
###################
# This package implements tools to build python package and tools.
# Copyright (C) 2022 Maurice Lambert
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
###################
"""
This package implements tools to build python package and tools.
>>> from urlopen import urlopen
>>> r = urlopen("http://google.com")
>>> r.code
200
>>> from urlopen import build_opener, httpcode
>>> @httpcode(301)
... def getstatuscode(s, r, f, c, m, h) -> int:
... return c
...
>>> urlopen = build_opener().open
>>> urlopen("http://google.com")
301
>>>
>>> from urlopen import build_opener, httpcode
>>> @httpcode(200, 500)
... def getstatuscode(s, r, f, c, m, h) -> int:
... return c
...
>>> urlopen = build_opener().open
>>> urlopen("https://google.com")
200
>>>
"""
__version__ = "0.0.4"
__author__ = "Maurice Lambert"
__author_email__ = "mauricelambert434@gmail.com"
__maintainer__ = "Maurice Lambert"
__maintainer_email__ = "mauricelambert434@gmail.com"
__description__ = """
This package implements tools to build python package and tools.
"""
license = "GPL-3.0 License"
__url__ = "https://github.com/mauricelambert/PythonToolsKit"
copyright = """
PythonToolsKit Copyright (C) 2022 Maurice Lambert
This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it
under certain conditions.
"""
__license__ = license
__copyright__ = copyright
__all__ = ["httpcode", "DefaultHandler", "build_opener"]
from urllib.request import (
build_opener,
Request,
OpenerDirector as _OpenerDirector,
BaseHandler,
HTTPRedirectHandler,
HTTPBasicAuthHandler,
ProxyBasicAuthHandler,
DataHandler,
HTTPHandler,
HTTPSHandler,
)
from http.client import HTTPResponse, HTTPMessage
from collections.abc import Callable, Sequence
from http import client as httpclient
from urllib.error import HTTPError
from typing import Dict, Any
from functools import wraps
from ssl import SSLContext
FUNCTIONS_CODES: Dict[int, Callable] = {
200: lambda s, r, f, c, m, h: f,
301: HTTPRedirectHandler().http_error_302,
302: HTTPRedirectHandler().http_error_302,
303: HTTPRedirectHandler().http_error_302,
307: HTTPRedirectHandler().http_error_302,
401: HTTPBasicAuthHandler().http_error_401,
407: ProxyBasicAuthHandler().http_error_407,
}
def httpcode(*args: Sequence[int]) -> Callable:
"""
This decorator change action on HTTP error
code.
"""
def decorator(function: Callable) -> Callable:
for code in args:
FUNCTIONS_CODES[code] = function
return function
return decorator
class OpenerDirector(_OpenerDirector):
def open(self, *args, context: SSLContext = None, **kwargs) -> Any:
"""
This function implements the default URL opener.
"""
if context is not None:
self.handlers[-1]._context = context
return super(OpenerDirector, self).open(*args, **kwargs)
def build_opener(functions: Dict[int, Callable] = None) -> OpenerDirector:
"""
This function creates an opener object
using default handlers.
"""
opener = OpenerDirector()
add_handler = opener.add_handler
add_handler(HTTPHandler())
add_handler(DataHandler())
if hasattr(httpclient, "HTTPSConnection"):
add_handler(HTTPSHandler())
add_handler(DefaultHandler(functions))
return opener
class DefaultHandler(BaseHandler):
"""
This class implements the default handler
for PythonToolsKit.urlopen.urlopen.
"""
max_repeats = 4
max_redirections = 10
auth_header = "Authorization"
def __init__(self, functions: Dict[int, Callable] = None):
functions = self.functions = functions or FUNCTIONS_CODES.copy()
self.functions_get = functions.get
def httpcode(self, *args: Sequence[int]) -> Callable:
"""
This decorator change action on HTTP error
code.
"""
def decorator(function: Callable) -> Callable:
for code in args:
FUNCTIONS_CODES[code] = function
return function
return decorator
def http_response(
self,
request: Request,
response: HTTPResponse,
) -> None:
code: int = response.code
message: str = response.msg
headers: HTTPMessage = response.info()
function = self.functions_get(code)
instance = getattr(function, "__self__", None)
if instance is not None:
instance.parent = self.parent
instance.handler_order = self.handler_order
args = (request, response, code, message, headers)
else:
args = (self, request, response, code, message, headers)
if function is not None:
return function(*args)
else:
raise NotImplementedError from HTTPError(
request.full_url, code, message, headers, response
)
https_response = http_response
urlopen = build_opener(FUNCTIONS_CODES).open