7
7
class Jokes :
8
8
def __init__ (self ):
9
9
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" ]
12
13
13
14
def build_request (
14
15
self ,
15
16
category = [],
16
17
blacklist = [],
17
18
response_format = "json" ,
18
- type = None ,
19
- search_string = None ,
20
- id_range = None ,
19
+ type = "Any" ,
20
+ search_string = "" ,
21
+ id_range = [] ,
21
22
amount = 1 ,
22
23
lang = "en"
23
24
):
24
25
r = "https://sv443.net/jokeapi/v2/joke/"
25
26
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 :
40
39
cats = "Any"
41
40
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 )
59
55
60
56
if response_format not in ["json" , "xml" , "yaml" , "txt" ]:
61
57
raise Exception (
62
58
"Response format must be either json, xml, txt or yaml."
63
59
)
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
+ )
73
65
74
66
if search_string :
75
67
if not isinstance (search_string , str ):
76
68
raise ValueError ("search_string must be a string." )
77
69
return
78
70
else :
79
71
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
+ )
93
85
94
86
r += cats
95
87
96
88
r += f"?format={ response_format } "
97
89
98
- if blacklistFlags :
99
- r += f"&blacklistFlags={ blacklistFlags } "
100
-
90
+ r += f"&blacklistFlags={ blacklistFlags } "
101
91
102
92
r += f"&type={ type } "
103
93
104
94
if search_string :
105
95
r += f"&contains={ search_string } "
106
96
if id_range :
107
97
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
- )
112
98
r += f"&amount={ amount } "
113
99
114
100
r += f"&lang={ lang } "
@@ -121,19 +107,20 @@ def send_request(self,
121
107
return_headers ,
122
108
auth_token ,
123
109
user_agent
124
- ):
110
+ ):
125
111
returns = []
126
112
127
113
if auth_token :
128
114
r = self .http .request ('GET' ,
129
115
request ,
130
116
headers = {'Authorization' : str (auth_token ),
131
117
'user-agent' : str (user_agent ),
132
- # 'accept-encoding': 'gzip'
133
- }
118
+ 'accept-encoding' : 'gzip'
119
+ }
134
120
)
135
121
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 )})
137
124
138
125
data = r .data .decode ('utf-8' )
139
126
@@ -144,9 +131,11 @@ def send_request(self,
144
131
print (data )
145
132
raise
146
133
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 } " )
150
139
151
140
headers = str (r .headers ).replace (r'\n' , '' ).replace (
152
141
'\n ' , '' ).replace (r'\\' , '' ).replace (r"\'" , '' )[15 :- 1 ]
@@ -156,7 +145,9 @@ def send_request(self,
156
145
returns .append (headers )
157
146
158
147
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 ]))})
160
151
161
152
if len (returns ) > 1 :
162
153
return returns
@@ -167,18 +158,31 @@ def get_joke(
167
158
category = [],
168
159
blacklist = [],
169
160
response_format = "json" ,
170
- type = None ,
171
- search_string = None ,
172
- id_range = None ,
161
+ type = "Any" ,
162
+ search_string = "" ,
163
+ id_range = [] ,
173
164
amount = 1 ,
174
165
lang = None ,
175
166
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" ,
177
169
return_headers = False
178
170
):
179
171
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
181
180
)
182
181
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 )
184
188
return response
0 commit comments