forked from PacktPublishing/AdvancedPythonProgramming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbridge.py
More file actions
73 lines (50 loc) · 1.61 KB
/
bridge.py
File metadata and controls
73 lines (50 loc) · 1.61 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
import abc
import urllib.parse
import urllib.request
class ResourceContent:
"""
Define the abstraction's interface.
Maintain a reference to an object which represents the Implementor.
"""
def __init__(self, imp):
self._imp = imp
def show_content(self, path):
self._imp.fetch(path)
class ResourceContentFetcher(metaclass=abc.ABCMeta):
"""
Define the interface (Implementor) for implementation classes that help fetch content.
"""
@abc.abstractmethod
def fetch(path):
pass
class URLFetcher(ResourceContentFetcher):
"""
Implement the Implementor interface and define its concrete
implementation.
"""
def fetch(self, path):
# path is an URL
req = urllib.request.Request(path)
with urllib.request.urlopen(req) as response:
if response.code == 200:
the_page = response.read()
print(the_page)
class LocalFileFetcher(ResourceContentFetcher):
"""
Implement the Implementor interface and define its concrete
implementation.
"""
def fetch(self, path):
# path is the filepath to a text file
with open(path) as f:
print(f.read())
def main():
url_fetcher = URLFetcher()
iface = ResourceContent(url_fetcher)
iface.show_content('http://python.org')
print('===================')
localfs_fetcher = LocalFileFetcher()
iface = ResourceContent(localfs_fetcher)
iface.show_content('file.txt')
if __name__ == "__main__":
main()