Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from flask import Flask, request, jsonify
|
3 |
+
from flask_cors import CORS
|
4 |
+
import requests
|
5 |
+
import pytz
|
6 |
+
from datetime import datetime, timedelta
|
7 |
+
|
8 |
+
app = Flask(__name__)
|
9 |
+
CORS(app)
|
10 |
+
|
11 |
+
# Load API key from environment variable
|
12 |
+
API_KEY = os.environ.get("CONV_TOKEN")
|
13 |
+
if not API_KEY:
|
14 |
+
raise ValueError("API Key not found! Set CONV_TOKEN environment variable.")
|
15 |
+
|
16 |
+
API_URL = f"https://v6.exchangerate-api.com/v6/{API_KEY}/latest/USD"
|
17 |
+
|
18 |
+
# Los Angeles timezone
|
19 |
+
LA_TZ = pytz.timezone("America/Los_Angeles")
|
20 |
+
|
21 |
+
# Cache storage
|
22 |
+
cached_rates = {}
|
23 |
+
last_updated = None # Store last update in LA time
|
24 |
+
|
25 |
+
def fetch_exchange_rates():
|
26 |
+
"""Fetch exchange rates from API and store them for 24 hours (Los Angeles time)."""
|
27 |
+
global cached_rates, last_updated
|
28 |
+
|
29 |
+
response = requests.get(API_URL)
|
30 |
+
if response.status_code == 200:
|
31 |
+
data = response.json()
|
32 |
+
cached_rates = data["conversion_rates"]
|
33 |
+
last_updated = datetime.now(LA_TZ) # Store timestamp in LA timezone
|
34 |
+
return True
|
35 |
+
return False
|
36 |
+
|
37 |
+
@app.route("/rate", methods=["GET"])
|
38 |
+
def get_exchange_rate():
|
39 |
+
"""Returns only the exchange rate for a given currency, refreshed every 24 hours (Los Angeles time)."""
|
40 |
+
global cached_rates, last_updated
|
41 |
+
|
42 |
+
from_currency = request.args.get("from", "").upper()
|
43 |
+
|
44 |
+
# Get current Los Angeles time
|
45 |
+
now_la = datetime.now(LA_TZ)
|
46 |
+
|
47 |
+
# If cache is older than 24 hours, refresh rates
|
48 |
+
if last_updated is None or (now_la - last_updated) > timedelta(hours=24):
|
49 |
+
success = fetch_exchange_rates()
|
50 |
+
if not success:
|
51 |
+
return jsonify({"error": "Failed to fetch exchange rates"}), 500
|
52 |
+
|
53 |
+
if from_currency in cached_rates:
|
54 |
+
return jsonify({
|
55 |
+
"from": from_currency,
|
56 |
+
"rate": cached_rates[from_currency],
|
57 |
+
"last_updated": last_updated.strftime("%Y-%m-%d %H:%M:%S %Z")
|
58 |
+
})
|
59 |
+
else:
|
60 |
+
return jsonify({"error": "Currency not supported"}), 400
|
61 |
+
|
62 |
+
if __name__ == "__main__":
|
63 |
+
fetch_exchange_rates() # Pre-load rates
|
64 |
+
app.run(host='0.0.0.0', port=7860)
|