Exemplo n.º 1
0
def populate_db():
    """Populates the cscourses.db database if it is empty. The Flask app needs to be running before you execute this code.

    :return: None
    """

    if not User.query.first():
        u1 = User( id=1, username="******", email='*****@*****.**')
        u2 = User( id=2, username="******", email="*****@*****.**")
        u3 = User( id=3, username="******", email="*****@*****.**")

        c1 = City( id=1, city="London" )
        c2 = City( id=2, city="Manchester" )

        f1 = Forecast( id=1, forecast="Rainy", forecast_datetime="2020-01-27 09:00:00",
                       comment="Take your umbrella !")

        u1.forecasts.append(f1)

        c1.forecasts.append(f1)

        db.session.add_all( [u1, u2, u3] )
        db.session.add_all( [c1, c2] )

        db.session.commit()
Exemplo n.º 2
0
def populate_db():
    """Populates the rain.db database if it is empty

    :return: None
    """

    if not User.query.first():
        db.session.add_all([
            User(user_id=123, username='******', email='*****@*****.**'),
            User(user_id=404, username="******", email="*****@*****.**"),
            User(user_id=456, username="******", email="*****@*****.**"),
            User(user_id=888, username="******", email="*****@*****.**")
        ])

    if not City.query.first():
        db.session.add_all([
            City(city_id=10001, city_name="London"),
            City(city_id=10002, city_name="Seoul")
        ])

    if not Forecast.query.first():
        db.session.add_all([
            Forecast(forecast_id=1234,
                     datetime="2020-02-20",
                     forecast="Sunny",
                     comment="Today is a very sunny day",
                     city_id=10001,
                     user_id=123),
            Forecast(forecast_id=1235,
                     datetime="2020-02-19",
                     forecast="Cloudy",
                     comment="Very cloudy, no sun.",
                     city_id=10002,
                     user_id=404),
            Forecast(forecast_id=1236,
                     datetime="2020-02-18",
                     forecast="Windy",
                     comment="Wind speed 50 mph!",
                     city_id=10001,
                     user_id=888)
        ])

    db.session.commit()
Exemplo n.º 3
0
def get_forecast(city_name):
    city = _get_city_by_name(city_name)

    data = _get_weather_by_city_id(city.woeid)
    if FORECAST_KEY in data:
        # get info for the current day
        f = Forecast().from_dict(data[FORECAST_KEY][0])
        return f
    else:
        raise AssertionError('Can not grab weather info for {}'.format(city_name))
Exemplo n.º 4
0
 def wrapper(*args, **kwargs):
     timestamp = kwargs.get('timestamp', None)
     if timestamp is None:
         return f(*args, **kwargs)
     try:
         cached = redis[timestamp]
     except KeyError:
         res = f(*args, **kwargs)
         redis[timestamp] = json.dumps(res.as_json())
         print('Wrote to Redis')
         return res
     print('Read from Redis')
     return Forecast(**json.loads(cached))
Exemplo n.º 5
0
def test_get_current_forecast(
    forecast: Forecast,
    client: FlaskClient,
    mocker: MockFixture,
):
    mocker.patch("app.api.v1.forecast.retrieve_forecast",
                 return_value=forecast)

    query = {"city": forecast.city}
    url = f'{url_for("api.get_current_forecast")}?{urlencode(query)}'
    resp: Response = client.get(url)

    assert resp.json == forecast.as_json()
Exemplo n.º 6
0
def retrieve_forecast(city: str,
                      timestamp: datetime,
                      units: Unit = Unit.CELSIUS) -> Forecast:
    query = {"appid": API_KEY, "q": city, "units": units.value}
    resp = requests.get(f"{API_URL}?{urlencode(query)}")

    if resp.status_code != 200:
        raise ValueError(f"Code is {resp.status_code}:\n{resp.content}")

    data = resp.json()
    temp = None
    for time in data["list"]:
        if time["dt"] == timestamp.timestamp():
            temp = time["main"]["temp"]
    if temp is None:
        raise ValueError("Temperature not found")
    return Forecast(city=data["city"]["name"], temperature=temp)
Exemplo n.º 7
0
def test_retrieve_forecast(city: str, temperature: float, time: datetime,
                           mocker: MockFixture):
    mock = MagicMock()
    mock.status_code = 200
    mock.json.return_value = {
        "city": {
            "name": city
        },
        "list": [{
            "dt": time.timestamp(),
            "main": {
                "temp": temperature
            }
        }],
    }

    mocker.patch("requests.get", return_value=mock)
    assert retrieve_forecast(city, time) == Forecast(city=city,
                                                     temperature=temperature)
Exemplo n.º 8
0
def main():
    # create a new session before executing inserts
    session = Session()

    # days grab in 24 hour chunks
    for day in range(1, 32):
        # get weather for month of march
        march = datetime(2018, 3, day).timestamp()
        # print(march)

        lat = 33.699657
        lon = -86.635033
        weather = get_weather(march, lat, lon)
        weather = filter_weather(weather)
        # print(weather)

        # select on lat, lon, time
        # make a new Forecast
        for w in weather:
            # print(**w)
            new_forecast = Forecast(latitude=lat, longitude=lon, **w)

            # match on lat, lon, time
            match = session.query(Forecast)\
            .filter(Forecast.latitude==lat)\
            .filter(Forecast.longitude==lon)\
            .filter(Forecast.time==w['time'])\
            .all()

            # if there were no matching records, insert
            if not match:
                print(f'Added: {new_forecast}')
                session.add(new_forecast)

        # save changes
    session.commit()
    print('DONE')
Exemplo n.º 9
0
def form_forecast(
    city: str, timestamp: str, temperature: float, unit: Unit = Unit.celsius
) -> Forecast:
    return Forecast(city=city, temperature=temperature, unit=unit)
Exemplo n.º 10
0
from datetime import datetime
from urllib.parse import urlencode

from flask import url_for, Response
from flask.testing import FlaskClient
from pytest_mock import MockFixture

from app.models import Forecast
from tests.helpers import autodetect_params, case


@autodetect_params()
@case(
    "With correct time",
    forecast=Forecast(city="Bob", temperature=100.500),
    time=datetime(2000, 1, 1, 1, 1),
)
def test_get_forecast(
    forecast: Forecast,
    time: datetime,
    client: FlaskClient,
    mocker: MockFixture,
):
    mocker.patch("app.api.v1.forecast.retrieve_forecast",
                 return_value=forecast)

    query = {"city": forecast.city, "dt": time.isoformat()}
    url = f'{url_for("api.get_forecast")}?{urlencode(query)}'
    resp: Response = client.get(url)

    assert resp.json == forecast.as_json()