Actualizar berretin.py

This commit is contained in:
nix 2025-11-07 20:05:28 +00:00
parent c16dc98e67
commit 50c4c9669f

View File

@ -4,7 +4,7 @@ import json
import requests import requests
import subprocess import subprocess
from datetime import datetime, timedelta from datetime import datetime, timedelta
from flask import Flask, jsonify, Response, request, abort from flask import Flask, jsonify, Response, request
BASE_API = "https://ws1.smn.gob.ar" BASE_API = "https://ws1.smn.gob.ar"
CACHE_DIR = "json.api.cache" CACHE_DIR = "json.api.cache"
@ -16,6 +16,7 @@ TIMEOUT = 10
app = Flask(__name__) app = Flask(__name__)
app.config["JSONIFY_PRETTYPRINT_REGULAR"] = False app.config["JSONIFY_PRETTYPRINT_REGULAR"] = False
@app.after_request @app.after_request
def remove_server_header(response): def remove_server_header(response):
response.headers["Server"] = "" response.headers["Server"] = ""
@ -27,6 +28,7 @@ def get_cache_filename(url: str) -> str:
h = hashlib.sha256(url.encode()).hexdigest() h = hashlib.sha256(url.encode()).hexdigest()
return os.path.join(CACHE_DIR, f"{h}.json") return os.path.join(CACHE_DIR, f"{h}.json")
def load_cache(url: str): def load_cache(url: str):
try: try:
path = get_cache_filename(url) path = get_cache_filename(url)
@ -40,6 +42,7 @@ def load_cache(url: str):
except Exception: except Exception:
return None return None
def save_cache(url: str, data: dict): def save_cache(url: str, data: dict):
try: try:
os.makedirs(CACHE_DIR, exist_ok=True) os.makedirs(CACHE_DIR, exist_ok=True)
@ -61,6 +64,7 @@ def load_smn_token():
print(f"[TOKEN] Error loading token: {e}") print(f"[TOKEN] Error loading token: {e}")
return "" return ""
def refresh_smn_token(): def refresh_smn_token():
print("[TOKEN] Refreshing SMN token...") print("[TOKEN] Refreshing SMN token...")
try: try:
@ -80,8 +84,10 @@ def refresh_smn_token():
def check_access_token(): def check_access_token():
header_token = request.headers.get("Authorization", "").strip() header_token = request.headers.get("Authorization", "").strip()
if not header_token or header_token != ACCESS_TOKEN: if header_token != ACCESS_TOKEN:
abort(401) # immediately reject unauthorized access # Drop unauthorized message (empty response)
return Response("", status=401)
return None
def fetch_from_smn(url: str, retry: bool = True): def fetch_from_smn(url: str, retry: bool = True):
@ -106,9 +112,11 @@ def fetch_from_smn(url: str, retry: bool = True):
return resp return resp
@app.route("/<path:subpath>") # change here bc nginx @app.route("/<path:subpath>")
def smn_proxy(subpath): def smn_proxy(subpath):
check_access_token() unauthorized = check_access_token()
if unauthorized:
return unauthorized
url = f"{BASE_API}/{subpath}" url = f"{BASE_API}/{subpath}"