|
| 1 | +from flask import Flask, render_template, request |
| 2 | +import requests |
| 3 | +import pycountry |
| 4 | + |
| 5 | +app = Flask(__name__) |
| 6 | + |
| 7 | +# ✅ Directly put your API key here (⚠️ not for public sharing) |
| 8 | +API_KEY = "b22be4aca453b5cb0870cc2f" |
| 9 | +API_URL = f"https://v6.exchangerate-api.com/v6/{API_KEY}/pair" |
| 10 | + |
| 11 | +# Get all ISO 4217 currencies (sorted) |
| 12 | +CURRENCIES = sorted([ |
| 13 | + (c.alpha_3, c.name) for c in pycountry.currencies |
| 14 | + if hasattr(c, 'alpha_3') and hasattr(c, 'name') |
| 15 | +]) |
| 16 | + |
| 17 | +@app.route('/') |
| 18 | +def index(): |
| 19 | + return render_template('index.html', currencies=CURRENCIES) |
| 20 | + |
| 21 | +@app.route('/convert', methods=['POST']) |
| 22 | +def convert(): |
| 23 | + try: |
| 24 | + amount = float(request.form['amount']) |
| 25 | + from_currency = request.form['from_currency'] |
| 26 | + to_currency = request.form['to_currency'] |
| 27 | + |
| 28 | + url = f"{API_URL}/{from_currency}/{to_currency}" |
| 29 | + response = requests.get(url) |
| 30 | + data = response.json() |
| 31 | + |
| 32 | + if data.get('result') == 'success': |
| 33 | + rate = data['conversion_rate'] |
| 34 | + converted = round(amount * rate, 2) |
| 35 | + result = f"{amount} {from_currency} = {converted} {to_currency}" |
| 36 | + else: |
| 37 | + result = "Conversion failed. Please check your currencies or API key." |
| 38 | + |
| 39 | + except Exception as e: |
| 40 | + result = f"Error: {str(e)}" |
| 41 | + |
| 42 | + return render_template('index.html', currencies=CURRENCIES, result=result) |
| 43 | + |
| 44 | +if __name__ == '__main__': |
| 45 | + app.run(debug=True) |
0 commit comments