1import re 2import json 3import requests 4from . import __version__ 5 6from .response import Works 7from .noworks import NoWorks 8 9# helpers ---------- 10def converter(x): 11 if x.__class__.__name__ == "str": 12 return [x] 13 else: 14 return x 15 16 17def sub_str(x, n=3): 18 if x.__class__.__name__ == "NoneType": 19 pass 20 else: 21 return str(x[:n]) + "***" 22 23 24def switch_classes(x, path, works): 25 if ( 26 works 27 or re.sub("/", "", path) == "works" 28 and re.sub("/", "", path) != "licenses" 29 ): 30 return Works(result=x) 31 else: 32 return NoWorks(result=x) 33 34 35def check_kwargs(keys, kwargs): 36 for x in range(len(keys)): 37 if keys[x] in kwargs.keys(): 38 mssg = "The %s parameter is not allowed with this method" % keys[x] 39 raise Exception(mssg) 40 41 42def check_json(x): 43 ctype = x.headers["Content-Type"] 44 matched = re.match("application/json", ctype) 45 if matched.__class__.__name__ == "NoneType": 46 scode = x.status_code 47 if str(x.text) == "Not implemented.": 48 scode = 400 49 raise RequestError(scode, str(x.text)) 50 51 52def is_json(x): 53 try: 54 json.loads(x.content) 55 except ValueError as e: # JSONDecodeError is a subclass of ValueError 56 return False 57 return True 58 59def parse_json_err(x): 60 return x.json()["message"][0]["message"] 61 62 63def make_ua(mailto=None, ua_string=None): 64 requa = "python-requests/" + requests.__version__ 65 habua = "habanero/%s" % __version__ 66 ua = requa + " " + habua 67 if mailto is not None: 68 ua = ua + " (mailto:%s)" % mailto 69 if ua_string is not None: 70 if not isinstance(ua_string, str): 71 raise TypeError("ua_string must be a str") 72 ua = ua + " " + ua_string 73 strg = {"User-Agent": ua, "X-USER-AGENT": ua} 74 return strg 75 76 77def filter_dict(x): 78 return dict((k, x[k]) for k, v in x.items() if k.find("query_") == 0) 79 80 81def rename_query_filters(x): 82 newkeys = [re.sub("container_title", "container-title", v) for v in x] 83 newkeys = [re.sub("query_", "query.", v) for v in newkeys] 84 mapping = dict(zip(x.keys(), newkeys)) 85 return {mapping[k]: v for k, v in x.items()} 86 87 88def ifelsestr(x): 89 z = str(x) if x is not None else x 90 return z 91