为什么我的asyncio代码有时能工作,而其他代码却不能?

2024-04-25 08:09:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我每5分钟运行一次这个代码,有时可以运行,有时不运行。我在django的网络应用程序里运行它。我正在使用代码在API和数据库之间进行同步。你知道吗

代码

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


class Command(BaseCommand):
    help = 'Updates the local database with Unbelievabot status'
    token = settings.UNBELIEVABOT_TOKEN
    client = Client(token)
    guild = Guild(settings.GUILD_ID)
    # loop = asyncio.get_event_loop()
    #asyncio.get_event_loop()

    def sync_unby_with_grid(self):
        # Grab all users with a discord ID
        users_with_discord = SocialAccount.objects.filter(provider='discord').values('user_id', 'uid')

        # Filter out results against leaderboard with total
        if users_with_discord:
            discord_ids_with_balance = Unbelievabot_Leaderboard.objects.filter(
                user_id__in=[x['uid'] for x in users_with_discord])

            # Build mapping to update each user
            for x in users_with_discord:
                for y in discord_ids_with_balance:
                    if y.user_id == x['uid']:
                        BankAccount.objects.filter(user=x['user_id']).update(unbelievabot_points=y.total)
        return

    def handle(self, *args, **options):

        board = loop.run_until_complete(Command.client.get_leaderboard(Command.guild))
        board_json = asyncio.run(board)

        for r in board_json:
            Unbelievabot_Leaderboard.objects.update_or_create(user_id=r['user_id'],
                                                              defaults={
                                                                  'rank': r['rank'],
                                                                  'cash': r['cash'],
                                                                  'bank': r['bank'],
                                                                  'total': r['total']
                                                              })
        self.sync_unby_with_grid()
        self.stdout.write(self.style.SUCCESS('Successfully Updated Database for "%s" accounts' % len(board_json)))

以下是回溯(未成功运行):

{'user_id': '342424242', 'cash': 291674, 'bank': 0, 'total': 291674, 'found': True}
    self._body = await self.content.read()
  File "/home/user/.virtualenvs/thegrid_v1/lib/python3.7/site-packages/aiohttp/streams.py", line 359, in read
    block = await self.readany()
  File "/home/user/.virtualenvs/thegrid_v1/lib/python3.7/site-packages/aiohttp/streams.py", line 381, in readany
    await self._wait('readany')
  File "/home/user/.virtualenvs/thegrid_v1/lib/python3.7/site-packages/aiohttp/streams.py", line 296, in _wait
    with self._timer:
  File "/home/user/.virtualenvs/thegrid_v1/lib/python3.7/site-packages/aiohttp/helpers.py", line 568, in __enter__
    raise RuntimeError('Timeout context manager should be used '
RuntimeError: Timeout context manager should be used inside a task

2019-09-14 19:05:47 -- Completed task, took 28.00 seconds, return code was 1.

成功运行

同样的功能在5分钟后可以正常运行 {'user\u id':'234234242','cash':292274,'bank':0,'total':292274,'found':True} 已成功更新“247”帐户的数据库

2019-09-14 20:05:54 -- Completed task, took 36.00 seconds, return code was 0.

Client类也在使用async并等待它的大多数方法,但我不确定这是否重要。我是asyncio的新手,我认为这可能会引起一些问题。你知道吗


Tags: inselfboardloopeventasyncioidfor