import os from flask import Flask, request, jsonify from flask_cors import CORS import requests import pytz from datetime import datetime, timedelta app = Flask(__name__) CORS(app) # Load API key from environment variable API_KEY = os.environ.get("CONV_TOKEN") if not API_KEY: raise ValueError("API Key not found! Set CONV_TOKEN environment variable.") API_URL = f"https://v6.exchangerate-api.com/v6/{API_KEY}/latest/USD" # Los Angeles timezone LA_TZ = pytz.timezone("America/Los_Angeles") # Cache storage cached_rates = {} last_updated = None # Store last update in LA time @app.route('/') def home(): return "" def fetch_exchange_rates(): """Fetch exchange rates from API and store them for 24 hours (Los Angeles time).""" global cached_rates, last_updated response = requests.get(API_URL) if response.status_code == 200: data = response.json() cached_rates = data["conversion_rates"] last_updated = datetime.now(LA_TZ) # Store timestamp in LA timezone return True return False @app.route("/rate", methods=["GET"]) def get_exchange_rate(): """Returns only the exchange rate for a given currency, refreshed every 24 hours (Los Angeles time).""" global cached_rates, last_updated from_currency = request.args.get("from", "").upper() # Get current Los Angeles time now_la = datetime.now(LA_TZ) # If cache is older than 24 hours, refresh rates if last_updated is None or (now_la - last_updated) > timedelta(hours=24): success = fetch_exchange_rates() if not success: return jsonify({"error": "Failed to fetch exchange rates"}), 500 if from_currency in cached_rates: return jsonify({ "from": from_currency, "rate": cached_rates[from_currency], "last_updated": last_updated.strftime("%Y-%m-%d %H:%M:%S %Z") }) else: return jsonify({"error": "Currency not supported"}), 400 if __name__ == "__main__": fetch_exchange_rates() # Pre-load rates app.run(host='0.0.0.0', port=7860)