# uso: fetch.py (registra en /w/datos/peticiones.jsonl; tope 40; pausa 3 s) import sys, json, time, hashlib, urllib.request, os LOG='/w/datos/peticiones.jsonl' n=sum(1 for _ in open(LOG)) if os.path.exists(LOG) else 0 if n>=40: sys.exit('TOPE 40 peticiones alcanzado') url,out=sys.argv[1],sys.argv[2] time.sleep(3) req=urllib.request.Request(url,headers={'User-Agent':'buscalicitaciones-investigacion (datos abiertos PMP)'}) rec={'n':n+1,'ts':time.strftime('%F %T'),'url':url} try: r=urllib.request.urlopen(req,timeout=120); b=r.read(); rec.update(code=r.status,final=r.geturl(),ctype=r.headers.get('Content-Type')) except urllib.error.HTTPError as e: b=e.read(); rec.update(code=e.code) rec.update(bytes=len(b),sha256=hashlib.sha256(b).hexdigest(),fichero=out) open('/w/datos/descargas/'+out,'wb').write(b) open(LOG,'a').write(json.dumps(rec,ensure_ascii=False)+'\n'); print(rec)