Jamiiwej2903 commited on
Commit
a27cd03
·
verified ·
1 Parent(s): ea9f7e5

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +8 -6
main.py CHANGED
@@ -1,6 +1,7 @@
1
  import asyncio
2
  import aiohttp
3
  from fastapi import FastAPI
 
4
  import logging
5
 
6
  logging.basicConfig(level=logging.INFO)
@@ -12,7 +13,7 @@ API_URL = "https://b917-160-179-178-105.ngrok-free.app/test-ai-call"
12
 
13
  call_count = 0
14
 
15
- async def call_api():
16
  global call_count
17
  async with aiohttp.ClientSession() as session:
18
  while True:
@@ -24,18 +25,19 @@ async def call_api():
24
  if response.status == 200:
25
  data = await response.json()
26
  logger.info(f"Call {call_count}: API Response: {data}")
 
27
  else:
28
  logger.error(f"Call {call_count}: API call failed with status code: {response.status}")
29
 
30
  except Exception as e:
31
  logger.error(f"Call {call_count}: Error: {e}")
32
 
33
- await asyncio.sleep(1)
34
 
35
- @app.on_event("startup")
36
- async def startup_event():
37
- asyncio.create_task(call_api())
38
 
39
  @app.get("/")
40
  async def root():
41
- return {"message": "API caller is running", "calls_made": call_count}
 
1
  import asyncio
2
  import aiohttp
3
  from fastapi import FastAPI
4
+ from sse_starlette.sse import EventSourceResponse
5
  import logging
6
 
7
  logging.basicConfig(level=logging.INFO)
 
13
 
14
  call_count = 0
15
 
16
+ async def event_generator():
17
  global call_count
18
  async with aiohttp.ClientSession() as session:
19
  while True:
 
25
  if response.status == 200:
26
  data = await response.json()
27
  logger.info(f"Call {call_count}: API Response: {data}")
28
+ yield data
29
  else:
30
  logger.error(f"Call {call_count}: API call failed with status code: {response.status}")
31
 
32
  except Exception as e:
33
  logger.error(f"Call {call_count}: Error: {e}")
34
 
35
+ await asyncio.sleep(10)
36
 
37
+ @app.get("/stream")
38
+ async def stream(request):
39
+ return EventSourceResponse(event_generator())
40
 
41
  @app.get("/")
42
  async def root():
43
+ return {"message": "API caller is running", "calls_made": call_count}