This commit is contained in:
Vadim Graboys 2019-08-17 19:14:32 +00:00 committed by GitHub
commit 010de3e2f1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 28 additions and 1 deletions

View File

@ -31,6 +31,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
@ -42,9 +52,14 @@ def buildNewsUrl(symbol, qs='&start=0&num=1000'):
+ symbol + qs
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:]

View File

@ -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()