@r1mple

Почему не работает семафор?

import aiohttp
import asyncio
import config
from bs4 import BeautifulSoup

URL = f'http://xmlriver.com/search/xml?user={config.USERID}&key={config.USERKEY}&groupby=100&loc=1007989&country=2376&lr=IW&domain=65&device=desktop&query='

keywords = ['start', 'test', 'demo']
results = []

async def fetch(query):
    async with aiohttp.ClientSession() as session:
        async with session.get(URL + query) as r:
            if r.status == 200:
                return await r.text()
            else:
                raise ConnectionError()

async def getUrl(semaphore):
    semaphore.acquire()
    print('1')
    # soup = BeautifulSoup(await fetch(query=query), 'html.parser')
    await asyncio.sleep(2)
    # print(str(soup.find_all('url')).replace('<url>', '').replace('</url>', ''))
    print('2')
    semaphore.release()

async def main():
    limit = asyncio.Semaphore(value=2)
    await asyncio.wait([getUrl(limit), getUrl(limit), getUrl(limit)])

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

на выходе:
1
1
1
2
2
2

Почему происходит так, ведь я явно указал в семафоре, что сначала выполняется 2 две функции?
  • Вопрос задан
  • 95 просмотров
Решения вопроса 1
Vindicar
@Vindicar
RTFM!
await semaphore.acquire()
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы