1 from datetime
import datetime
2 from feed
import XmlFeed
3 from utils
import unescape
4 from xml
.dom
import minidom
9 def __init__(self
, key_fml
):
10 self
.key_fml
= key_fml
11 self
.fml_cache
= {} # xml-elements # 10-quotes cache
12 self
.qdb_cache
= {} # {'quotes': xml-elements, 'ts': datetime-timestamp, 'next': next quote index}
// page cached
for 15s
14 def get_qdb_random(self
):
15 if not self
.qdb_cache
or (datetime
.now() - self
.qdb_cache
['ts']).seconds
> 15:
16 qdb
= XmlFeed('http://qdb.us/qdb.xml?action=random&fixed=0')
17 quotes
= qdb
.elements('//item')
19 self
.qdb_cache
= {'quotes': quotes, 'ts': datetime.now(), 'next': next}
21 quotes
= self
.qdb_cache
['quotes']
22 next
= self
.qdb_cache
['next']
25 self
.qdb_cache
['next'] = next
+ 1
26 lines
= unescape(quote
.text('description')).split('<br />')
28 return self
.get_qdb_random()
30 return {'lines': lines, 'link': quote.text('link'), 'id': quote.text('title')}
32 def get_qdb_id(self
, quote_id
):
33 qdb
= XmlFeed('http://qdb.us/qdb.xml?action=quote"e=%d&fixed=0' % quote_id
)
34 quotes
= qdb
.elements('//item')
37 lines
= unescape(quote
.text('description')).split('<br />')
39 return {'lines': ['this quote is too long. You can view it here: %s' % quote.text('link')], 'link': quote.text('link'), 'id': quote.text('title')}
41 return {'lines': lines, 'link': quote.text('link'), 'id': quote.text('title')}
45 def _get_fml_quotes(self
, url
):
46 feed
= minidom
.parse(urllib
.urlopen(url
))
47 return feed
.getElementsByTagName('item')
49 def get_fml(self
, quote_id
=None):
50 """Grab either the given quote (by id), or just a random one."""
51 if quote_id
is None: # if we're doing a random quote
52 # for random quotes, we request 10 at a time, then repopulate our cache when it runs out
53 if not self
.fml_cache
:
54 self
.fml_cache
= self
._get
_fml
_quotes
('http://api.fmylife.com/view/random/10/nocomment?key=%s&language=en' % self
.key_fml
)
56 if len(self
.fml_cache
) == 0:
57 raise FmlException("fmylife.com is temporarily unavailable. Please try again later.")
59 quote
= self
.fml_cache
.pop()
62 quote
= self
._get
_fml
_quotes
('http://api.fmylife.com/view/%d/nocomment?key=%s&language=en' % (quote_id
, self
.key_fml
))[0]
64 text
= quote
.getElementsByTagName('text')[0].toxml()[6:-7]
65 id = quote
.getAttribute('id')
66 category
= quote
.getElementsByTagName('category')[0].toxml()[10:-11]
68 return {'text': unescape(text), 'id': id, 'category': category}
71 class FmlException(Exception):
72 def __init__(self
, e
):