Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1import os 

2 

3from requests import Session as RequestsSession 

4from requests.exceptions import Timeout, ConnectionError 

5 

6from webapp.api.exceptions import ApiConnectionError, ApiTimeoutError 

7 

8 

9class GeventGreenletTimeout(Exception): 

10 pass 

11 

12 

13class BaseSession: 

14 """A base session interface to implement common functionality 

15 

16 Create an interface to manage exceptions and return API exceptions 

17 """ 

18 

19 def __init__(self, *args, **kwargs): 

20 super().__init__(*args, **kwargs) 

21 

22 # TODO allow user to choose it's own user agent 

23 storefront_header = "storefront ({commit_hash};{environment})".format( 

24 commit_hash=os.getenv("COMMIT_ID", "commit_id"), 

25 environment=os.getenv("ENVIRONMENT", "devel"), 

26 ) 

27 headers = {"User-Agent": storefront_header, "Connection": "close"} 

28 self.headers.update(headers) 

29 

30 def request(self, method, url, timeout=12, **kwargs): 

31 try: 

32 return super().request( 

33 method=method, url=url, timeout=timeout, **kwargs 

34 ) 

35 except Timeout: 

36 raise ApiTimeoutError( 

37 "The request to {} took too long".format(url) 

38 ) 

39 except ConnectionError: 

40 raise ApiConnectionError( 

41 "Failed to establish connection to {}.".format(url) 

42 ) 

43 

44 

45class Session(BaseSession, RequestsSession): 

46 pass 

47 

48 

49class PublisherSession(BaseSession, RequestsSession): 

50 def request(self, method, url, timeout=None, **kwargs): 

51 return super().request(method, url, timeout, **kwargs)