88import xml .etree .ElementTree
99
1010import requests
11+ from requests .adapters import HTTPAdapter
12+ from urllib3 .util .retry import Retry
1113from bs4 import BeautifulSoup
1214from jinja2 import Template
1315import yaml
@@ -32,6 +34,23 @@ def mkdir_safe(directory):
3234 pass
3335
3436
37+ def fetch (url , ** kwargs ):
38+ """Retry transient upstream failures without sharing sessions across threads."""
39+ retries = Retry (
40+ total = 3 ,
41+ backoff_factor = 1 ,
42+ status_forcelist = (500 , 502 , 503 , 504 ),
43+ allowed_methods = frozenset (["GET" ]),
44+ raise_on_status = False ,
45+ )
46+ with requests .Session () as session :
47+ session .mount ("https://" , HTTPAdapter (max_retries = retries ))
48+ session .mount ("http://" , HTTPAdapter (max_retries = retries ))
49+ response = session .get (url , timeout = (10 , 30 ), ** kwargs )
50+ response .raise_for_status ()
51+ return response
52+
53+
3554def get_list (soup , pre_title ):
3655 """
3756 Blocks of links are preceded by a `p` saying what it is.
@@ -114,8 +133,7 @@ def create_episode(api_episode, show_config, output_dir):
114133
115134 links = html2text .html2text (str (get_list (api_soup , "Links:" ) or get_list (api_soup , "Episode Links:" )))
116135
117- page_request = requests .get (api_episode ["url" ], headers = {"Accept" : "text/html" })
118- page_request .raise_for_status ()
136+ page_request = fetch (api_episode ["url" ], headers = {"Accept" : "text/html" })
119137
120138 page_soup = BeautifulSoup (page_request .content , "html.parser" )
121139
@@ -195,7 +213,7 @@ def api_data_from_rss_item(item):
195213
196214
197215def scrape_episodes_from_rss (url ):
198- raw_xml = requests . get (url ).content
216+ raw_xml = fetch (url ).content
199217 feed = xml .etree .ElementTree .fromstring (raw_xml )
200218 channel = feed .find ("channel" )
201219 assert channel is not None , "channel not found!"
@@ -233,13 +251,14 @@ def main():
233251
234252 try :
235253 api_data = (
236- requests . get (show_config ["fireside_url" ] + "/json" ).json ()["items" ]
254+ fetch (show_config ["fireside_url" ] + "/json" ).json ()["items" ]
237255 if show_config .get ("use_fireside_json" )
238256 else scrape_episodes_from_rss (show_config ["fireside_url" ] + "/rss" )
239257 )
240258 for api_episode in api_data :
241259 futures .append (executor .submit (create_episode , api_episode , show_config , output_dir ))
242260 except Exception as e :
261+ exit_code = 1
243262 print ("ERROR: An error occurred somewhere." )
244263 traceback .print_exception (e )
245264
0 commit comments