mirror of
https://github.com/hongtaocai/googlefinance.git
synced 2025-02-25 18:55:20 -06:00
add optional timeout
Prevents hanging threads due to network issues.
This commit is contained in:
parent
82a558da72
commit
0e42c4d1d6
@ -30,6 +30,16 @@ googleFinanceKeyToFullName = {
|
||||
u'pcls_fix': u'PreviousClosePrice'
|
||||
}
|
||||
|
||||
DEFAULT_TIMEOUT = None
|
||||
_timeout = DEFAULT_TIMEOUT
|
||||
|
||||
def setTimeout(timeoutSeconds):
|
||||
'''
|
||||
Sets the timeout for google finance API calls (in seconds).
|
||||
'''
|
||||
global _timeout
|
||||
_timeout = timeoutSeconds
|
||||
|
||||
def buildUrl(symbols):
|
||||
symbol_list = ','.join([symbol for symbol in symbols])
|
||||
# a deprecated but still active & correct api
|
||||
@ -37,9 +47,14 @@ def buildUrl(symbols):
|
||||
+ symbol_list
|
||||
|
||||
def request(symbols):
|
||||
urlopenFlags = {}
|
||||
if _timeout is not None:
|
||||
urlopenFlags['timeout'] = _timeout
|
||||
|
||||
url = buildUrl(symbols)
|
||||
req = Request(url)
|
||||
resp = urlopen(req)
|
||||
resp = urlopen(req, **urlopenFlags)
|
||||
|
||||
# remove special symbols such as the pound symbol
|
||||
content = resp.read().decode('ascii', 'ignore').strip()
|
||||
content = content[3:]
|
||||
|
@ -1,5 +1,6 @@
|
||||
import googlefinance
|
||||
import unittest
|
||||
from urllib2 import URLError
|
||||
|
||||
class TestQuotes(unittest.TestCase):
|
||||
|
||||
@ -15,3 +16,14 @@ class TestQuotes(unittest.TestCase):
|
||||
self.assertEqual(quotes[1]["Index"], "VIE")
|
||||
self.assertEqual(quotes[1]["StockSymbol"], "BKS")
|
||||
|
||||
def test_timeout(self):
|
||||
# ensure timeout will always happen
|
||||
googlefinance.setTimeout(0.0001)
|
||||
with self.assertRaisesRegexp(URLError, 'timed out'):
|
||||
googlefinance.getQuotes(['GOOG'])
|
||||
|
||||
# reset timeout (for other tests)
|
||||
googlefinance.setTimeout(googlefinance.DEFAULT_TIMEOUT)
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
Loading…
Reference in New Issue
Block a user