为什么我的异步代码有时可以工作,而其他却不能工作?

时间:2019-09-14 22:24:47

标签: python django python-asyncio virtualenvwrapper

我每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_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的新手,并认为这可能会引起一些问题。

0 个答案:

没有答案