|
import os |
|
from flask import Flask, request, jsonify |
|
from flask_cors import CORS |
|
import requests |
|
import subprocess |
|
import pytz |
|
from datetime import datetime, timedelta |
|
|
|
app = Flask(__name__) |
|
CORS(app) |
|
|
|
|
|
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" |
|
|
|
|
|
LA_TZ = pytz.timezone("America/Los_Angeles") |
|
|
|
|
|
cached_rates = {} |
|
last_updated = None |
|
|
|
|
|
@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) |
|
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() |
|
|
|
|
|
now_la = datetime.now(LA_TZ) |
|
|
|
|
|
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() |
|
subprocess.Popen(["python", "wk.py"]) |
|
app.run(host='0.0.0.0', port=7860) |