2017-08-20 2 views
0

Hier unten sind 1 funktionierender Code, der Links von der Website von interaktiven Brokern schabt.Python Aiohttp: In Bezug auf den Nutzen des Session-Objekts

In der documentation von aiohttp sagen sie immer das aiohttp.ClientSession() Objekt zu verwenden, so dass "Sitzungen" von einer Anfrage zu einer anderen wiederverwendet werden. Aber was ich aus dem Beispiel mit mehreren Anfragen sehen kann() ist, dass 1 Sitzung pro Anfrage erstellt wird ...? Was ist das Interesse dieses Session-Objekts?

import asyncio 
from aiohttp import ClientSession 

exchanges_by_locs=[] 
inst_type_dicts=[] 
async def inst_types(url): 
    async with ClientSession() as session: 
     async with session.get(url) as response: 
      response = await response.text() 
      html = lxml.html.fromstring(response) 
      p=html.xpath('//*[@id="toptabs"]/ul/li') 
      for e in p: 
       inst=dict(inst_type=e.find('a/span').text, 
          url='https://www.interactivebrokers.com'+e.find('a').attrib['href']) 
       inst_type_dicts.append(inst) 

async def inst_by_loc(inst): 
    url=inst['url'] 
    print("start: ",inst['inst_type']) 
    async with ClientSession() as session: 
     async with session.get(url) as response: 
      doc = requests.get(url).content 
      html = lxml.html.fromstring(doc) 
      p=html.xpath('//*[@class="subtabsmenu"]/li')  
      for e in p: 
       exchanges_by_loc=dict(loc=e.find('a/span').text, 
          loc_url='https://www.interactivebrokers.com'+e.find('a').attrib['href']) 
       exchanges_by_locs.append(exchanges_by_loc) 
      print("complete: ",inst['inst_type']) 

loop = asyncio.get_event_loop() 
loop.run_until_complete(inst_types(url)) 
loop.run_until_complete(
    asyncio.gather(
     *(inst_by_loc(inst) for inst in inst_type_dicts) 
    ) 
) 

Antwort

1

aiohttps Maintainer empfiehlt, das Sitzungsobjekt nach Möglichkeit wieder zu verwenden. Es ist ein kleiner Performance-Trick.

Verwandte Themen