AsyncIO:尽管在 Django 中使用了 AsyncIO,程序仍然以同步方式运行

问题描述 投票:0回答:1

我创建了一个名为

APIDummyWait5
的 API。
现在我想测试以下内容
- 我希望 API 在几毫秒内返回结果。
- 虽然 API 内部调用的函数应该以异步方式运行。

API -

APIDummyWait5
随机生成 1 - 25 之间的数字,然后将其作为参数发送给名为
get_country_details
的函数以及我将从 API url 参数中获取的另一个名为 Country 的参数。

这是API

class APIDummyWait5(APIView):
    def get(self, request):
        print("Coming Here")
        worker = os.getpid()
        thread = threading.get_ident()

        country = request.GET.get('country')

        print(f"API wait 5 - for worker - {worker} at Thread {thread} starting at: {datetime.datetime.now()}")

        wait_time = rd.randint(1, 25)
        response = {'wait_time': wait_time, 'country': country}

        asyncio.run(main(wait_time=wait_time, country=country))

        print(f"API Wait 5 - for worker - {worker} at Thread {thread} ending at: {datetime.datetime.now()}")

        return Response({
            "data": response
        })
async def main(wait_time, country):
    result = await get_country_details(wait_time, country)

我正在创建一个名为

main
的辅助函数来调用
get_country_details
函数。

该函数 -

get_country_details
实际上会休眠等待时间,然后调用第三方 API 来获取国家/地区的名称和首都并将其存储在 csv 中。

async def get_country_details(wait_time, country):
    worker = os.getpid()

    print(f"API Quick @ {wait_time} - for worker - {worker} starting at: {datetime.datetime.now()}")

    await asyncio.sleep(wait_time)  # Simulate waiting time

    url = f"https://restcountries.com/v3.1/name/{country}"
    
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            if response.status == 200:
                data = await response.json()
                
                file = pd.read_csv('country_data.csv')
                name_list = list(file['name'])
                capital_list = list(file['capital'])

                country_data = data[0]
                country = country_data['name']['common']
                capital = country_data['capital'][0]

                name_list.append(country)
                capital_list.append(capital)

                new_data = pd.DataFrame({'name': name_list, 'capital': capital_list})
                new_data.to_csv('country_data.csv', index=False)

                print(f"Asynchronously Ran Function for {wait_time} seconds.")
                return 1
            else:
                print(f"Error: Unable to fetch details for {country}")
                return None

现在如果 wait_time = 11
然后需要 11 秒才能返回响应,而由于主 API 并不耗时,因此应该在 XX 毫秒内返回响应。

为什么它仍然以同步方式运行?我应该如何解决这个问题?
我不想使用线程,我正在使用 asyncio 测试一些东西。

python django async-await python-asyncio
1个回答
0
投票

尝试将

asyncio.run(main(wait_time=wait_time, country=country))
替换为
asyncio.create_task(main(wait_time=wait_time, country=country))

class APIDummyWait5(APIView):
def get(self, request):
    print("Coming Here")
    worker = os.getpid()
    thread = threading.get_ident()

    country = request.GET.get('country')

    print(f"API wait 5 - for worker - {worker} at Thread {thread} starting at: {datetime.datetime.now()}")

    wait_time = rd.randint(1, 25)
    response = {'wait_time': wait_time, 'country': country}

    asyncio.create_task(main(wait_time=wait_time, country=country))

    print(f"API Wait 5 - for worker - {worker} at Thread {thread} ending at: {datetime.datetime.now()}")

    return Response({
        "data": response
    })
© www.soinside.com 2019 - 2024. All rights reserved.