簡體   English   中英

我不確定為什么我在 python 中遇到此異步錯誤

[英]I'm not sure why im getting this async error in python

我設法讓我的 api 請求異步,但在嘗試將其實施到主項目時收到此錯誤。 這意味着我做錯了什么?

錯誤

Exception has occurred: SynchronousOnlyOperation
You cannot call this from an async context - use a thread or sync_to_async.
  File "C:\Users\Admin\Desktop\djangoProjects\dguac\Signal.py", line 124, in main
    await asyncio.wait([sigBuy(count) for count, bot in enumerate(activeBots)])
  File "C:\Users\Admin\Desktop\djangoProjects\dguac\Signal.py", line 126, in <module>
    loop.run_until_complete(main())

我不明白這個錯誤是什么意思以及我將如何解決它。

這是我的代碼

async def sigBuy(count):

            bot_dict = Bot.to_dict(activeBots[count])
            sigSettings_dict = Bot.to_dict(activeBots[count].sigSettings)

            # Binance API and Secret Keys
            Bclient = CryptoXLib.create_binance_client(sigSettings_dict['API_key'], sigSettings_dict['API_secret_key'])
            
            p = round(float(percentage(7, bot_dict['ct_balance']) / (float(bin_asset_price['price']) / 1)), 8)
            # Round and Asign the asset_amount
            asset_amount = round(p, 2)

            # shouldILog = await makeBuy(market, asset_amount, Bclient, sigSettings_dict['base_currency'])
            shouldILog = 2
            if shouldILog == 2:
                asset_amount = int(asset_amount)

            last_trade = await Bclient.get_all_orders(pair = Pair(market, sigSettings_dict['base_currency']))
            last_trade = last_trade['response'][-1]
            print(last_trade)

            # asset_price = float(last_trade['cummulativeQuoteQty']) / float(last_trade['executedQty'])
            asset_price = 0.00000123
            buyInPrice = float(last_trade['cummulativeQuoteQty'])

            for otrade in activeBots[count].opentrades.all():
                trade = Bot.to_dict(otrade)
                del trade['id']
                otradesUpdate.append(trade)
            
            openTrades_dict = {'bot_ID': bot_dict['id'], 'date': date, 'market': market, 'trade_mode': 'Buy', 'price': asset_price, 'amount': asset_amount, 'amount_in_base_currency': buyInPrice, 'result': 0}

            otradesUpdate.append(openTrades_dict)
            BotsUpdate.append(bot_dict)
            SigSettingsUpdate.append(sigSettings_dict)

            await Bclient.close()


        async def main():
            await asyncio.wait([sigBuy(count) for count, bot in enumerate(activeBots)])
        
        loop.run_until_complete(main())

await asyncio.wait 似乎是正確的,因為您可以擁有一個可迭代列表(即使 asyncio.wait 應該被棄用 iirc),但異常消息有點讓我失望。 OP 應該做的是圍繞 Django ORM 的查詢集並讓它執行,但是 Django 的 ORM 延遲加載可能會導致一些問題。


錯誤的原始答案

你不是在等待正確的事情。 你的意思是等待 sigBuy 但你的 asyncio.wait 正在等待。 與此同時,您現在擁有一個未執行任何操作的協程列表。

我建議你嘗試兩件事:

  • 如果您想同時運行,請保留列表但不要等待它。 相反,使用 asyncio.gather 同時運行它們。 asyncio.gather([sigBuy(count) for count, bot in enumerate(activeBots)])
  • 如果您想一次運行它們,請確保列表理解的工作方式相同: [await sigBuy(count) for count, bot in enumerate(activeBots)]

我通過使用解決了這個錯誤

    async def main():
        await asyncio.wait([sigBuy(count) for count, bot in enumerate(activeBots)])

    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(main())

並且首先將過濾和預取的 django 查詢中的每個項目附加到新的 activeBots 列表中,以便異步代碼接受它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM