Alvin3y1 commited on
Commit
75f3b2f
·
verified ·
1 Parent(s): a6d8311

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +16 -1
app.py CHANGED
@@ -287,11 +287,26 @@ async def handle_data(request):
287
  "history": market_state['history']
288
  })
289
 
 
 
 
 
 
 
 
 
 
 
 
 
290
  async def main():
291
  app = web.Application()
292
  app.router.add_get('/', handle_index)
293
  app.router.add_get('/data', handle_data)
294
- app.on_startup.append(lambda a: a.__setitem__('t', asyncio.create_task(kraken_worker())))
 
 
 
295
 
296
  runner = web.AppRunner(app)
297
  await runner.setup()
 
287
  "history": market_state['history']
288
  })
289
 
290
+ async def start_background(app):
291
+ """Correct way to start background task in aiohttp"""
292
+ app['kraken_task'] = asyncio.create_task(kraken_worker())
293
+
294
+ async def cleanup_background(app):
295
+ """Correct way to cleanup background task"""
296
+ app['kraken_task'].cancel()
297
+ try:
298
+ await app['kraken_task']
299
+ except asyncio.CancelledError:
300
+ pass
301
+
302
  async def main():
303
  app = web.Application()
304
  app.router.add_get('/', handle_index)
305
  app.router.add_get('/data', handle_data)
306
+
307
+ # Register startup and cleanup handlers safely
308
+ app.on_startup.append(start_background)
309
+ app.on_cleanup.append(cleanup_background)
310
 
311
  runner = web.AppRunner(app)
312
  await runner.setup()