Я работаю над сценарием, который запросит URL -адреса набора данных (CSV, JSON, PDF, HTML, иногда XML) из конечной точки Sparql Sparql. CSVS).
Однако, несмотря на тайм -аут , скрипт по -прежнему висит - без исключений, без вывода и отсутствия прогресса.
Я подозреваю некоторые конечные точки (особенно. бесконечно . Мне нужен жесткий срез - если нет ответа, например, 15 секунд, скрипт должен продолжаться без блокировки.
import requests
from bs4 import BeautifulSoup
from PyPDF2 import PdfReader
from io import BytesIO
import json
def fetch_preview(url: str, max_lines: int = 5) -> str:
"""
Fetches a short preview of a dataset from various formats.
Hangs for some URLs – suspecting request timeout isn't enforced?
"""
if "service=wms" in url.lower() or url.lower().endswith((".wms",)):
return "(Preview not available for WMS services)"
try:
# This sometimes hangs indefinitely – even with timeout?
resp = requests.get(url, timeout=10)
resp.raise_for_status()
except Exception as e:
return f"(Error loading: {e})"
ctype = resp.headers.get("Content-Type", "").lower()
if "csv" in ctype or url.lower().endswith(".csv"):
return "\n".join(resp.text.splitlines()[:max_lines])
if "application/json" in ctype or url.lower().endswith(".json"):
try:
data = resp.json()
if isinstance(data, list):
snippet = data[:max_lines]
else:
keys = list(data.keys())[:max_lines]
snippet = {k: data[k] for k in keys}
return json.dumps(snippet, ensure_ascii=False, indent=2)
except:
return "(Invalid JSON)"
if "html" in ctype or url.lower().endswith((".html", ".htm")):
soup = BeautifulSoup(resp.text, "html.parser")
paras = soup.find_all("p", limit=max_lines)
return "\n".join(p.get_text().strip() for p in paras)
if "xml" in ctype or url.lower().endswith((".xml", ".gml")) or "wfs" in url.lower():
return "\n".join(resp.text.splitlines()[:max_lines])
if "pdf" in ctype or url.lower().endswith(".pdf"):
try:
reader = PdfReader(BytesIO(resp.content))
if reader.pages:
text = reader.pages[0].extract_text() or ""
return "\n".join(text.splitlines()[:max_lines])
except:
return "(PDF could not be read)"
return "(Unknown format)"
Подробнее здесь: https://stackoverflow.com/questions/796 ... on-slow-br
Requests.get () по -прежнему висит, несмотря на тайм -аут - как заставить жесткое отсечение на медленных/сломанных URL? ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Вызывает ли сбой тайм-аут сторожевого таймера или тайм-аут является результатом сбоя?
Anonymous » » в форуме Linux - 0 Ответы
- 157 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Почему Python httpx.get или Requests.get намного медленнее, чем cURL для этого API?
Anonymous » » в форуме Python - 0 Ответы
- 39 Просмотры
-
Последнее сообщение Anonymous
-