-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchucknorris.py
executable file
·47 lines (36 loc) · 1.09 KB
/
chucknorris.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import json
import sys
if sys.version < '3':
from urllib2 import urlopen
from urllib import quote as urlquote
else:
from urllib.request import urlopen
from urllib.parse import quote as urlquote
# chuck norris database API
CND_RANDOM_URL = 'http://api.icndb.com/jokes/random'
class ChuckNorrisDefinition(object):
def __init__(self, id, joke):
self.id = id
self.joke = joke
def __str__(self):
return "%s" % (self.joke)
def _get_chuckn_json(url):
f = urlopen(url)
data = json.loads(f.read().decode('utf-8'))
f.close()
return data
def _parse_chuckn_json(json, check_result=True):
if json is None or any(e in json for e in ('error', 'errors')):
raise ValueException('CN: Invalid input for Chuck Norris API')
if check_result and json['type'] != 'success':
return []
data = json['value']
d = ChuckNorrisDefinition(
data['id'],
data['joke']
)
return d
def random():
"""Return random joke"""
json = _get_chuckn_json(CND_RANDOM_URL)
return _parse_chuckn_json(json, check_result=False)