1
+ import urllib
1
2
import aiohttp
2
3
import simplejson as json
3
4
import re
4
- import pprint
5
5
6
6
7
7
class CategoryError (Exception ):
@@ -37,6 +37,21 @@ async def post(session, url, data, headers=None):
37
37
return response_text , response .headers
38
38
39
39
40
+ # https://stackoverflow.com/a/36724229
41
+ class AsyncIterator :
42
+ def __init__ (self , seq ):
43
+ self .iter = iter (seq )
44
+
45
+ def __aiter__ (self ):
46
+ return self
47
+
48
+ async def __anext__ (self ):
49
+ try :
50
+ return next (self .iter )
51
+ except StopIteration :
52
+ raise StopAsyncIteration
53
+
54
+
40
55
class Joke_Class :
41
56
async def init (self ):
42
57
async with aiohttp .ClientSession () as session :
@@ -56,10 +71,10 @@ async def build_request(
56
71
safe_mode = False ,
57
72
lang = "en" ,
58
73
):
59
- r = "https://v2.jokapi .dev/joke/"
74
+ r = "https://v2.jokeapi .dev/joke/"
60
75
61
76
if len (category ):
62
- async for c in category :
77
+ async for c in AsyncIterator ( category ) :
63
78
if not c .title () in self .info ["categories" ]:
64
79
raise CategoryError (
65
80
f'''Invalid category selected.
@@ -185,9 +200,10 @@ async def send_request(
185
200
print (r )
186
201
raise
187
202
else :
203
+ data = r
188
204
if (
189
205
len (
190
- " " .join (re .split ("error" , r .lower ())[0 :][1 :])
206
+ " " .join (re .split ("error" , data .lower ())[0 :][1 :])
191
207
.replace ("<" , "" )
192
208
.replace ("/" , "" )
193
209
.replace (" " , "" )
@@ -305,12 +321,9 @@ async def submit_joke(
305
321
request ["lang" ] = lang
306
322
307
323
data = json .dumps (request ).replace ("'" , '"' )
308
- print (data )
309
324
data = data .encode ("ascii" )
310
325
url = f"https://v2.jokeapi.dev/submit{ '?dry-run' * dry_run } "
311
326
312
-
313
- pprint .pprint (data )
314
327
if auth_token :
315
328
headers = {
316
329
"Authorization" : str (auth_token ),
0 commit comments