我有 Python 中的 TD API,我试图从多引号 api 门户获取 423 个引号,但它并不总是返回 423。这听起来像异步情况吗?这是我实现异步的尝试,但我确定我没有做对。任何指针?
n = symbols_list
payload = {'symbol':n}
content = requests.get(url = endpoint, params = payload, headers = headers)
data = content.json()
time.sleep(1)
async def get(
session: aiohttp.ClientSession,
n: str,
**kwargs
) -> dict:
url = endpoint
headers = headers
print(f"Requesting {url}")
resp = await session.request('GET', url=url, **kwargs)
# Note that this may raise an exception for non-2xx responses
# You can either handle that here, or pass the exception through
data = await resp.json()
print('Received data for {url}')
return data
async def main(n, **kwargs):
# Asynchronous context manager. Prefer this rather
# than using a different session for each GET request
async with aiohttp.ClientSession() as session:
tasks = []
for symbols in n:
try:
tasks.append(get(session=session, n=symbols, **kwargs))
payload = {'symbol':symbols}
a = data
b = a[symbols]['symbol']
c = a[symbols]['lastPrice']
d = a[symbols]['netChange']
e = a[symbols]['totalVolume']
f = a[symbols]['regularMarketLastPrice']
g = a[symbols]['highPrice']
h = a[symbols]['lowPrice']
quotes = pd.DataFrame({'symbol' : [symbols], 'last' : [c], 'change' : [d], 'volume' : [e]
,'OOCLast' : [f], 'high' : [g], 'low' : [h]})
quotes.to_sql(name='quotes', con=engine, if_exists='append')
except:
pass
# asyncio.gather() will wait on the entire task set to be
# completed. If you want to process results greedily as they come in,
# loop over asyncio.as_com#pleted()
htmls = await asyncio.gather(*tasks, return_exceptions=True)
return htmls
if __name__ == '__main__':
n = symbols_list
# ...
# Either take colors from stdin or make some default here
await main(n)