general_posts/python-weather-api/api/views.py

53 lines
1.5 KiB
Python

from flask import jsonify
from flask import request
from flask.views import MethodView
from functools import wraps
from api.error import Error
ALLOWED_API_KEY = "TEST_KEY"
def check_api_key(f):
@wraps(f)
def decorated_function(*args, **kwargs):
api_key = request.args.get('api_key')
if api_key != ALLOWED_API_KEY:
return jsonify({"error": "Unauthorized Request"}), 401
return f(*args, **kwargs)
return decorated_function
class BaseView(MethodView):
def __init__(self, service=None):
self.service=service
class HistoricWeatherView(BaseView):
@check_api_key
def get(self, location, date=None):
try:
weather_data = self.service.get_historic_weather(location, date)
return jsonify({"data": weather_data}), 200
except Error as e:
return jsonify({"error": e.message}), e.status_code
class CurrentWeatherView(BaseView):
@check_api_key
def get(self, location):
try:
current_data = self.service.get_current_weather(location)
return jsonify({"data": current_data}), 200
except Error as e:
return jsonify({"error": e.message}), e.status_code
class ForecastWeatherView(BaseView):
@check_api_key
def get(self, location):
try:
forecast_data = self.service.get_forecast_weather(location)
return jsonify({"data": forecast_data}), 200
except Error as e:
return jsonify({"error": e.message}), e.status_code