Spaces:
Sleeping
Sleeping
File size: 2,031 Bytes
6c57252 | 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 | from flask import Flask, request, jsonify
from flask_cors import CORS
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
import requests
import time
app = Flask(__name__)
CORS(app)
# Rate Limiter Configuration
# 1000 per day (Hard limit), 60 per hour, 5 per minute per IP
limiter = Limiter(
get_remote_address,
app=app,
default_limits=["1000 per day", "60 per hour", "10 per minute"],
storage_uri="memory://"
)
API_KEY = "0a4f51067c3f1588b9e0c0fa4b313986"
BASE_URL = "https://api.openweathermap.org/data/2.5"
# Simple In-Memory Cache to save API calls
# key: city_name, value: {timestamp, data}
weather_cache = {}
CACHE_DURATION = 600 # 10 minutes
@app.route('/weather', methods=['GET'])
@limiter.limit("1000 per day")
def get_weather():
city = request.args.get('city')
if not city:
return jsonify({'error': 'City is required'}), 400
city = city.lower().strip()
# Check Cache
current_time = time.time()
if city in weather_cache:
cached_data, timestamp = weather_cache[city]
if current_time - timestamp < CACHE_DURATION:
return jsonify({**cached_data, 'source': 'cache'})
# Fetch from OpenWeather
try:
response = requests.get(f"{BASE_URL}/weather", params={
'q': city,
'appid': API_KEY,
'units': 'metric'
})
if response.status_code != 200:
return jsonify({'error': 'City not found'}), response.status_code
data = response.json()
# Save to Cache
weather_cache[city] = (data, current_time)
return jsonify({**data, 'source': 'api'})
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/health', methods=['GET'])
def health():
return jsonify({'status': 'online', 'limit': '1000/day'})
if __name__ == '__main__':
import os
port = int(os.environ.get('PORT', 7860))
app.run(host='0.0.0.0', port=port)
|