keep-alive / main.py
pvanand's picture
Update main.py
8e5de0e verified
Raw History Blame Contribute Delete
3.52 kB
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from apscheduler.schedulers.background import BackgroundScheduler
import hrequests
from datetime import datetime, timedelta
import random
import logging
app = FastAPI()
# Set up logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# List of links to check
links = [
"https://multi-agent-research-v190.streamlit.app",
"https://multi-agent-research-v22.streamlit.app",
"https://news-agent-v1.streamlit.app",
"https://multi-agent-code-v130.streamlit.app",
"https://code-interpreter-v21.streamlit.app",
"https://code-interpreter-v22.streamlit.app",
"https://code-agent-v10.streamlit.app",
"https://career-agent.streamlit.app",
"https://investorv2.streamlit.app",
"https://ppt-agent-v1.streamlit.app",
"https://docu-mind.streamlit.app",
"https://article-extraction.streamlit.app"
]
# Dictionary to store link status and last checked time
link_status = {link: {"status": "Not checked", "last_checked": "Never"} for link in links}
def check_link(link):
try:
logger.debug(f"Checking link: {link}")
resp = hrequests.get(link, browser='chrome')
status = f"OK ({resp.status_code})" if resp.status_code < 400 else f"Error ({resp.status_code})"
link_status[link] = {"status": status, "last_checked": datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
logger.info(f"Checked {link} - Status: {status}")
except Exception as e:
link_status[link] = {"status": f"Error: {str(e)}", "last_checked": datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
logger.error(f"Error checking {link}: {str(e)}")
def schedule_checks():
now = datetime.now()
end_time = now + timedelta(hours=6)
for link in links:
# Schedule a random time within the 6-hour window
schedule_time = now + timedelta(seconds=random.randint(0, 6 * 60 * 60))
if schedule_time <= end_time:
scheduler.add_job(check_link, 'date', run_date=schedule_time, args=[link])
logger.debug(f"Scheduled check for {link} at {schedule_time}")
scheduler = BackgroundScheduler()
scheduler.start()
@app.on_event("startup")
async def startup_event():
logger.info("Application starting up. Scheduling link checks...")
schedule_checks()
@app.get("/", response_class=HTMLResponse)
async def root():
html_content = """
<html>
<head>
<title>Link Checker Dashboard</title>
<style>
table { border-collapse: collapse; width: 100%; }
th, td { border: 1px solid black; padding: 8px; text-align: left; }
th { background-color: #f2f2f2; }
</style>
</head>
<body>
<h1>Link Checker Dashboard</h1>
<table>
<tr>
<th>Link</th>
<th>Status</th>
<th>Last Checked</th>
</tr>
"""
for link, data in link_status.items():
html_content += f"""
<tr>
<td>{link}</td>
<td>{data['status']}</td>
<td>{data['last_checked']}</td>
</tr>
"""
html_content += """
</table>
</body>
</html>
"""
return HTMLResponse(content=html_content)
if __name__ == "__main__":
import uvicorn
logger.info("Starting the application...")
uvicorn.run(app, host="0.0.0.0", port=8000)