forked from jaraco/cssutils
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_fetch.py
More file actions
64 lines (53 loc) · 1.84 KB
/
_fetch.py
File metadata and controls
64 lines (53 loc) · 1.84 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
"""Default URL reading functions"""
__all__ = ['_defaultFetcher']
import functools
import urllib.error
import urllib.request
try:
from importlib import metadata
except ImportError:
import importlib_metadata as metadata
import encutils
from . import errorhandler
log = errorhandler.ErrorHandler()
@functools.lru_cache
def _get_version():
try:
return metadata.version('cssutils')
except metadata.PackageNotFoundError:
return 'unknown'
def _defaultFetcher(url):
"""Retrieve data from ``url``. cssutils default implementation of fetch
URL function.
Returns ``(encoding, string)`` or ``None``
"""
try:
request = urllib.request.Request(url)
agent = f'cssutils/{_get_version()} (https://pypi.org/project/cssutils)'
request.add_header('User-agent', agent)
res = urllib.request.urlopen(request)
except urllib.error.HTTPError as e:
# http error, e.g. 404, e can be raised
log.warn(f'HTTPError opening url={url}: {e.code} {e.msg}', error=e)
except urllib.error.URLError as e:
# URLError like mailto: or other IO errors, e can be raised
log.warn('URLError, %s' % e.reason, error=e)
except OSError as e:
# e.g if file URL and not found
log.warn(e, error=OSError)
except ValueError as e:
# invalid url, e.g. "1"
log.warn('ValueError, %s' % e.args[0], error=ValueError)
else:
if res:
mimeType, encoding = encutils.getHTTPInfo(res)
if mimeType != 'text/css':
log.error(
'Expected "text/css" mime type for url=%r but found: %r'
% (url, mimeType),
error=ValueError,
)
content = res.read()
if hasattr(res, 'close'):
res.close()
return encoding, content