forked from PacktPublishing/AdvancedPythonProgramming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsingleton.py
More file actions
57 lines (40 loc) · 1.33 KB
/
singleton.py
File metadata and controls
57 lines (40 loc) · 1.33 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
import urllib.parse
import urllib.request
class SingletonType(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(SingletonType, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class URLFetcher(metaclass=SingletonType):
def __init__(self):
self.urls = []
def fetch(self, url):
req = urllib.request.Request(url)
with urllib.request.urlopen(req) as response:
if response.code == 200:
the_page = response.read()
print(the_page)
urls = self.urls
urls.append(url)
self.urls = urls
def dump_url_registry(self):
return ', '.join(self.urls)
def main():
MY_URLS = ['http://www.voidspace.org.uk',
'http://google.com',
'http://python.org',
'https://www.python.org/error',
]
print(URLFetcher() is URLFetcher())
fetcher = URLFetcher()
for url in MY_URLS:
try:
fetcher.fetch(url)
except Exception as e:
print(e)
print('-------')
done_urls = fetcher.dump_url_registry()
print(f'Done URLs: {done_urls}')
if __name__ == '__main__':
main()