File size: 2,143 Bytes
07b1927
 
 
 
48190e9
07b1927
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c3e0456
 
 
 
 
 
 
 
07b1927
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48190e9
07b1927
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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)

# 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
    subprocess.Popen(["python", "wk.py"])
    app.run(host='0.0.0.0', port=7860)