general_posts/python-weather-api/app.py

54 lines
1.7 KiB
Python

from flask import Flask
from database import Database
DATABASE_URL = "sqlite:///weather.db"
def create_app(config_object={}):
app = Flask(__name__)
app.config.from_object(config_object)
app.json.sort_keys = False
database = Database(DATABASE_URL)
@app.after_request
def after_request(response):
database.session.close()
return response
configure_blueprints(app, database)
return app
def configure_blueprints(app, database):
from api.views import HistoricWeatherView
from api.views import CurrentWeatherView
from api.views import ForecastWeatherView
from api.services import HistoricWeatherService
from api.services import CurrentWeatherService
from api.services import ForecastWeatherService
historic_service = HistoricWeatherService(database=database)
current_service = CurrentWeatherService(database=database)
forecast_service = ForecastWeatherService(database=database)
historic_view = HistoricWeatherView.as_view("historic", service=historic_service)
app.add_url_rule('/api/historical/<string:location>', view_func=historic_view, methods=["GET"])
app.add_url_rule('/api/historical/<string:location>/<string:date>', view_func=historic_view, methods=["GET"])
current_view = CurrentWeatherView.as_view("current", service=current_service)
app.add_url_rule('/api/current/<string:location>', view_func=current_view, methods=["GET"])
forecast_view = ForecastWeatherView.as_view("forecast", service=forecast_service)
app.add_url_rule('/api/forecast/<string:location>', view_func=forecast_view, methods=["GET"])
if __name__ == "__main__":
app = create_app({})
app.run(host="127.0.0.1", port=5000, debug=True)