"""Peticiones al servicio de búsqueda de TED para el cotejo de E-S1 (DEFINICIONES_PREVIAS §6). Uso: python3 pedir.py lote.json -> cada elemento {"id":..., "query":..., "fields":[...], "limit":N} Límites: tope total 100 peticiones (contador persistente), >= 6 s entre peticiones, parada con 403/429, UA del proyecto sin correo. Registro de cada petición en /c/cotejo/peticiones.log.""" import json, sys, time, os, urllib.request, urllib.error BASE = '/c/cotejo' UA = 'buscalicitaciones.com-investigacion/1.0 (+https://buscalicitaciones.com)' URL = 'https://api.ted.europa.eu/v3/notices/search' TOPE = 100 cnt_f = f'{BASE}/contador.txt' n = int(open(cnt_f).read()) if os.path.exists(cnt_f) else 0 lote = json.load(open(sys.argv[1])) log = open(f'{BASE}/peticiones.log', 'a') for q in lote: if n >= TOPE: print('TOPE de 100 peticiones alcanzado'); break if q.get("get"): req = urllib.request.Request(q["get"], method='GET', headers={'User-Agent': UA}) q["query"] = 'GET ' + q["get"] else: body = {"query": q["query"], "fields": q["fields"], "page": 1, "limit": q.get("limit", 50), "scope": "ALL", "checkQuerySyntax": False, "paginationMode": "PAGE_NUMBER"} data = json.dumps(body).encode() req = urllib.request.Request(URL, data=data, method='POST', headers={'User-Agent': UA, 'Accept': 'application/json', 'Content-Type': 'application/json'}) t0 = time.strftime('%Y-%m-%d %H:%M:%S') try: with urllib.request.urlopen(req, timeout=60) as r: st, txt = r.status, r.read().decode('utf-8', 'replace') except urllib.error.HTTPError as e: st, txt = e.code, e.read().decode('utf-8', 'replace') except Exception as e: st, txt = -1, repr(e) n += 1 open(cnt_f, 'w').write(str(n)) open(f'{BASE}/resp/{q["id"]}' + ('.xml' if q.get('get') else '.json'), 'w').write(txt) log.write(f'{t0}\t#{n}\t{q["id"]}\tPOST {URL}\t{q["query"]}\tHTTP {st}\t{len(txt)} B\n'); log.flush() print(n, q['id'], st, len(txt), flush=True) if st in (403, 429): print('PARADA por', st); break time.sleep(6)