77class Jokes :
88 def __init__ (self ):
99 self .http = urllib3 .PoolManager ()
10- self .info = self .http .request ('GET' , "https://sv443.net/jokeapi/v2/info" )
11- self .info = data = json .loads (self .info .data .decode ('utf-8' ))["jokes" ]
10+ self .info = self .http .request (
11+ 'GET' , "https://sv443.net/jokeapi/v2/info" )
12+ self .info = json .loads (self .info .data .decode ('utf-8' ))["jokes" ]
1213
1314 def build_request (
1415 self ,
1516 category = [],
1617 blacklist = [],
1718 response_format = "json" ,
18- type = None ,
19- search_string = None ,
20- id_range = None ,
19+ type = "Any" ,
20+ search_string = "" ,
21+ id_range = [] ,
2122 amount = 1 ,
2223 lang = "en"
2324 ):
2425 r = "https://sv443.net/jokeapi/v2/joke/"
2526
26- if len (category ):
27- for c in category :
28- if not c .title () in self .info ["categories" ]:
29- raise ValueError (
30- f'''Invalid category selected.
31- You selected { c } .
32- Available categories are:
33- { """
34- """ .join (self .info ["categories" ])}
35- Leave blank for any.'''
36- )
37-
38- cats = "," .join (category )
39- else :
27+ if any (c not in self .info ["categories" ] for c in category ):
28+ raise ValueError (
29+ f'''Invalid category selected.
30+ You selected { c } .
31+ Available categories are:
32+ { """
33+ """ .join (self .info ["categories" ])}
34+ Leave blank for any.'''
35+ )
36+
37+ cats = "," .join (category )
38+ if not cats :
4039 cats = "Any"
4140
42- if len (blacklist ) > 0 :
43- for b in blacklist :
44- if b not in self .info ["flags" ]:
45- raise ValueError (
46- f'''
47-
48-
49- You have blacklisted flags which are not available or you have not put the flags in a list.
50- Available flags are:
51- { """
52- """ .join (self .info ["flags" ])}
53- '''
54- )
55- return
56- blacklistFlags = "," .join (blacklist )
57- else :
58- blacklistFlags = None
41+ if any (b not in self .info ["flags" ] for b in blacklist ):
42+ raise ValueError (
43+ f'''
44+
45+
46+ You have blacklisted flags which are not available or \
47+ you have not put the flags in a list.
48+ Available flags are:
49+ { """
50+ """ .join (self .info ["flags" ])}
51+ '''
52+ )
53+ return
54+ blacklistFlags = "," .join (blacklist )
5955
6056 if response_format not in ["json" , "xml" , "yaml" , "txt" ]:
6157 raise Exception (
6258 "Response format must be either json, xml, txt or yaml."
6359 )
64- if type :
65- if type not in ["single" , "twopart" ]:
66- raise ValueError (
67- '''Invalid joke type.
68- Available options are "single" or "twopart".'''
69- )
70- return
71- else :
72- type = "Any"
60+ if type not in ["single" , "twopart" , "Any" ]:
61+ raise ValueError (
62+ '''Invalid joke type.
63+ Available options are "single" or "twopart".'''
64+ )
7365
7466 if search_string :
7567 if not isinstance (search_string , str ):
7668 raise ValueError ("search_string must be a string." )
7769 return
7870 else :
7971 search_string = urllib .parse .quote (search_string )
80- if id_range :
81- range_limit = self . info [ "totalCount" ]
82-
83- if len ( id_range ) > 2 :
84- raise ValueError ( "id_range must be no longer than 2 items." )
85- elif id_range [0 ] < 0 :
86- raise ValueError (
87- "id_range[0] must be greater than or equal to 0."
88- )
89- elif id_range [ 1 ] > range_limit :
90- raise ValueError (
91- f"id_range[1] must be less than or equal to { range_limit - 1 } ."
92- )
72+ range_limit = self . info [ "totalCount" ]
73+
74+ if len ( id_range ) and ( id_range [ 1 ] - id_range [ 0 ] > range_limit ):
75+ raise ValueError (
76+ "id_range must be no longer than 2 items, \
77+ id_range[0] must be greater than or equal to 0 and \
78+ id_range[1] must be less than or equal to {range_limit-1}." )
79+
80+ if amount > 10 :
81+ raise ValueError (
82+ f"amount parameter must be no greater than 10. \
83+ you passed { amount } ."
84+ )
9385
9486 r += cats
9587
9688 r += f"?format={ response_format } "
9789
98- if blacklistFlags :
99- r += f"&blacklistFlags={ blacklistFlags } "
100-
90+ r += f"&blacklistFlags={ blacklistFlags } "
10191
10292 r += f"&type={ type } "
10393
10494 if search_string :
10595 r += f"&contains={ search_string } "
10696 if id_range :
10797 r += f"i&dRange={ id_range [0 ]} -{ id_range [1 ]} "
108- if amount > 10 :
109- raise ValueError (
110- f"amount parameter must be no greater than 10. you passed { amount } ."
111- )
11298 r += f"&amount={ amount } "
11399
114100 r += f"&lang={ lang } "
@@ -121,19 +107,20 @@ def send_request(self,
121107 return_headers ,
122108 auth_token ,
123109 user_agent
124- ):
110+ ):
125111 returns = []
126112
127113 if auth_token :
128114 r = self .http .request ('GET' ,
129115 request ,
130116 headers = {'Authorization' : str (auth_token ),
131117 'user-agent' : str (user_agent ),
132- # 'accept-encoding': 'gzip'
133- }
118+ 'accept-encoding' : 'gzip'
119+ }
134120 )
135121 else :
136- r = self .http .request ('GET' , request , headers = {'user-agent' : str (user_agent )})
122+ r = self .http .request ('GET' , request , headers = {
123+ 'user-agent' : str (user_agent )})
137124
138125 data = r .data .decode ('utf-8' )
139126
@@ -144,9 +131,11 @@ def send_request(self,
144131 print (data )
145132 raise
146133 else :
147- if len (' ' .join (re .split ("error" , data .lower ().replace ("\n " , "NEWLINECHAR" ))[0 :][1 :]).replace (
148- '<' , '' ).replace ('/' , '' ).replace (' ' , '' ).replace (':' , '' ).replace ('>' , '' ).replace ('NEWLINECHAR' , '\n ' )) == 4 :
149- return [Exception (f"API returned an error. Full response: \n \n { data } " )]
134+ if len (' ' .join (re .split ("error" , data .lower ())[0 :][1 :]).replace (
135+ '<' , '' ).replace ('/' , '' ).replace (' ' , '' ).replace (':' , '' )
136+ .replace ('>' , '' )) == 4 :
137+ raise Exception (f"API returned an error. \
138+ Full response: \n \n { data } " )
150139
151140 headers = str (r .headers ).replace (r'\n' , '' ).replace (
152141 '\n ' , '' ).replace (r'\\' , '' ).replace (r"\'" , '' )[15 :- 1 ]
@@ -156,7 +145,9 @@ def send_request(self,
156145 returns .append (headers )
157146
158147 if auth_token :
159- returns .append ({"Token-Valid" : bool (int (re .split (r"Token-Valid" , headers )[1 ][4 ]))})
148+ returns .append (
149+ {"Token-Valid" : bool (int (re .split (r"Token-Valid" ,
150+ headers )[1 ][4 ]))})
160151
161152 if len (returns ) > 1 :
162153 return returns
@@ -167,18 +158,31 @@ def get_joke(
167158 category = [],
168159 blacklist = [],
169160 response_format = "json" ,
170- type = None ,
171- search_string = None ,
172- id_range = None ,
161+ type = "Any" ,
162+ search_string = "" ,
163+ id_range = [] ,
173164 amount = 1 ,
174165 lang = None ,
175166 auth_token = None ,
176- user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0" ,
167+ user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) \
168+ Gecko/20100101 Firefox/77.0" ,
177169 return_headers = False
178170 ):
179171 r = self .build_request (
180- category , blacklist , response_format , type , search_string , id_range , amount , lang
172+ category ,
173+ blacklist ,
174+ response_format ,
175+ type ,
176+ search_string ,
177+ id_range ,
178+ amount ,
179+ lang
181180 )
182181
183- response = self .send_request (r , response_format , return_headers , auth_token , user_agent )
182+ response = self .send_request (
183+ r ,
184+ response_format ,
185+ return_headers ,
186+ auth_token ,
187+ user_agent )
184188 return response
0 commit comments