]> git.phdru.name Git - bookmarks_db.git/blob - Robots/bkmk_rurllib2.py
Refactor(Robots): Refactor request headers
[bookmarks_db.git] / Robots / bkmk_rurllib2.py
1 """Robot based on urllib2
2
3 This file is a part of Bookmarks database and Internet robot.
4
5 """
6
7 __author__ = "Oleg Broytman <phd@phdru.name>"
8 __copyright__ = "Copyright (C) 2014-2024 PhiloSoft Design"
9 __license__ = "GNU GPL"
10
11 __all__ = ['robot_urllib2']
12
13
14 import sys
15 import httplib
16 import urllib2
17 from Robots.bkmk_robot_base import robot_base, request_headers, get_error
18
19
20 _fw = None
21
22
23 class FTPHandler(urllib2.FTPHandler):
24     def connect_ftp(self, user, passwd, host, port, dirs, timeout):
25         global _fw
26         _fw = urllib2.FTPHandler.connect_ftp(self, user, passwd, host, port,
27                                              dirs, timeout)
28         return _fw
29
30
31 opener = urllib2.OpenerDirector()
32 default_classes = [urllib2.HTTPHandler, urllib2.HTTPDefaultErrorHandler,
33                    FTPHandler, urllib2.HTTPErrorProcessor]
34 if hasattr(httplib, 'HTTPS'):
35     default_classes.insert(0, urllib2.HTTPSHandler)
36 for klass in default_classes:
37     opener.add_handler(klass())
38
39 urllib2.install_opener(opener)
40
41
42 class robot_urllib2(robot_base):
43     def get(self, bookmark, url, accept_charset=False):
44         request = urllib2.Request(url)
45         for h, v in request_headers.items():
46             request.add_header(h, v)
47         if accept_charset and bookmark.charset:
48             request.add_header('Accept-Charset', bookmark.charset)
49
50         global _fw
51         _fw = None
52
53         try:
54             response = urllib2.urlopen(request)
55
56         except urllib2.HTTPError as e:
57             if e.code in (301, 302, 303, 307, 308):
58                 return None, e.code, e.hdrs['Location'], None, None
59             else:
60                 self.log('   HTTP Error %s: %s' % (e.code, e.msg))
61                 return ("HTTP Error %s: %s" % (e.code, e.msg),
62                         None, None, None, None)
63
64         except urllib2.URLError as e:
65             self.log('   URL Error: %s' % e.reason)
66             return "URL Error: %s" % e.reason, None, None, None, None
67
68         except httplib.HTTPException as e:
69             error = get_error(e)
70             self.log('   HTTP Exception: %s' % error)
71             return "HTTP Exception: %s" % error, None, None, None, None
72
73         except IOError as e:
74             error = get_error(e)
75             self.log('   I/O Error: %s' % error)
76             return "I/O Error: %s" % error, None, None, None, None
77
78         else:
79             return None, None, None, response.info(), response.read()
80
81     def get_ftp_welcome(self):
82         if _fw is None:
83             return ''
84         return _fw.ftp.welcome