]> git.phdru.name Git - bookmarks_db.git/blob - Robots/bkmk_rrequests.py
Feat: For the robot based on requests allow to use a proxy
[bookmarks_db.git] / Robots / bkmk_rrequests.py
1 """Robot based on requests
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) 2024 PhiloSoft Design"
9 __license__ = "GNU GPL"
10
11 __all__ = ['robot_requests']
12
13
14 import requests
15 import requests_ftp
16
17 from Robots.bkmk_robot_base import robot_base
18
19 requests_ftp.monkeypatch_session()
20
21
22 class robot_requests(robot_base):
23     # Pass proxy from the environment like this:
24     # BKMK_ROBOT=requests:proxy=socks5h%3a//localhost%3a1080
25     proxy = None
26
27     def get(self, bookmark, url, accept_charset=False):
28         try:
29             r = requests.Session().get(
30                 url, timeout=self.timeout, allow_redirects=False)
31         except requests.RequestException as e:
32             error = str(e)
33             self.log('   Error: %s' % error)
34             if self.proxy:
35                 error = None
36                 self.log('   Retrying with the proxy...')
37                 try:
38                     r = requests.get(
39                         url, timeout=self.timeout, allow_redirects=False,
40                         proxies={'http': self.proxy, 'https': self.proxy})
41                 except requests.RequestException as e:
42                     error = str(e)
43                     self.log('   Proxy error: %s' % error)
44             if error is not None:
45                 return error, None, None, None, None
46         if r.is_redirect:
47             return None, r.status_code, r.next.url, None, None
48         return None, None, None, r.headers, r.content
49
50     def get_ftp_welcome(self):
51         return ''  # Alas, requests_ftp doesn't store welcome message