Skip to content

Commit 433db70

Browse files
authored
feat(api): Add a check when posting a new task if the url is reachable (#105)
1 parent 9d631d6 commit 433db70

File tree

4 files changed

+1387
-1274
lines changed

4 files changed

+1387
-1274
lines changed

bases/ecoindex/backend/routers/tasks.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,17 @@
11
from json import loads
22

3+
import requests
34
from celery.result import AsyncResult
45
from ecoindex.backend.models.dependencies_parameters.id import IdParameter
56
from ecoindex.backend.utils import check_quota
67
from ecoindex.config.settings import Settings
78
from ecoindex.database.engine import get_session
89
from ecoindex.models import WebPage
910
from ecoindex.models.enums import TaskStatus
10-
from ecoindex.models.response_examples import example_daily_limit_response
11+
from ecoindex.models.response_examples import (
12+
example_daily_limit_response,
13+
example_host_unreachable,
14+
)
1115
from ecoindex.models.tasks import QueueTaskApi, QueueTaskResult
1216
from ecoindex.worker.tasks import ecoindex_task
1317
from ecoindex.worker_component import app as task_app
@@ -26,6 +30,7 @@
2630
status.HTTP_201_CREATED: {"model": str},
2731
status.HTTP_403_FORBIDDEN: {"model": str},
2832
status.HTTP_429_TOO_MANY_REQUESTS: example_daily_limit_response,
33+
521: example_host_unreachable,
2934
},
3035
description="This submits a ecoindex analysis task to the engine",
3136
status_code=status.HTTP_201_CREATED,
@@ -54,6 +59,16 @@ async def add_ecoindex_analysis_task(
5459
detail="This host is excluded from the analysis",
5560
)
5661

62+
try:
63+
r = requests.head(url=web_page.url, timeout=5)
64+
r.raise_for_status()
65+
except Exception:
66+
print(f"The URL {web_page.url} is not reachable")
67+
raise HTTPException(
68+
status_code=521,
69+
detail=f"The URL {web_page.url} is unreachable. Are you really sure of this url? 🤔",
70+
)
71+
5772
task_result = ecoindex_task.delay(
5873
url=str(web_page.url), width=web_page.width, height=web_page.height
5974
)

components/ecoindex/models/response_examples.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,3 +117,14 @@
117117
}
118118
},
119119
}
120+
121+
example_host_unreachable = {
122+
"description": "Host unreachable",
123+
"content": {
124+
"application/json": {
125+
"example": {
126+
"detail": "The URL http://localhost is unreachable. Are you really sure of this url? 🤔",
127+
}
128+
}
129+
},
130+
}

0 commit comments

Comments
 (0)