Skip to content

Commit

Permalink
fix: reuse aiohttp client session to prevent crash
Browse files Browse the repository at this point in the history
  • Loading branch information
shidenggui committed Oct 13, 2016
1 parent 9391c46 commit 270e12b
Showing 1 changed file with 7 additions and 2 deletions.
9 changes: 7 additions & 2 deletions easyquotation/basequotation.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ class BaseQuotation:
stock_api = '' # 股票 api

def __init__(self):
self._session = None
stock_codes = self.load_stock_codes()
self.stock_list = self.gen_stock_list(stock_codes)

Expand All @@ -28,7 +29,8 @@ def gen_stock_list(self, stock_codes):
stock_list.append(request_list)
return stock_list

def load_stock_codes(self):
@staticmethod
def load_stock_codes():
with open(helpers.stock_code_path()) as f:
return json.load(f)['stock']

Expand All @@ -47,12 +49,14 @@ async def get_stocks_by_range(self, params):
headers = {
'Accept-Encoding': 'gzip'
}
async with aiohttp.ClientSession().get(self.stock_api + params, timeout=5, headers=headers) as r:
async with self._session.get(self.stock_api + params, timeout=5, headers=headers) as r:
response_text = await r.text()
return response_text

def get_stock_data(self, stock_list):
self._session = aiohttp.ClientSession()
coroutines = []

for params in stock_list:
coroutine = self.get_stocks_by_range(params)
coroutines.append(coroutine)
Expand All @@ -63,6 +67,7 @@ def get_stock_data(self, stock_list):
asyncio.set_event_loop(loop)
res = loop.run_until_complete(asyncio.gather(*coroutines))

self._session.close()
return self.format_response_data(res)

def format_response_data(self, rep_data):
Expand Down

0 comments on commit 270e12b

Please sign in to comment.