Skip to content
Snippets Groups Projects
Select Git revision
  • e0043e396ae2150b7a65930d8180ad15674b042d
  • main default protected
2 results

main.py

Blame
  • main.py 2.13 KiB
    from kivy.app import App
    from kivy.uix.boxlayout import BoxLayout
    from kivy.uix.label import Label
    from kivy.properties import ListProperty
    from kivy.logger import Logger
    
    from datetime import datetime
    
    from api_key import API_KEY
    from rest import RESTConnection
    
    
    UNL_LATITUDE = 40.8207
    UNL_LONGITUDE = -96.7005
    UNITS = 'imperial'
    
    
    def to_human_readable_time(timestamp):
        return datetime.fromtimestamp(timestamp).strftime('%A %I:%M %p')
    
    
    def format_forecast_record(record):
        try:
            time = to_human_readable_time(record['dt'])
            description = ', '.join(condition['description'] for condition in record['weather'])
            temperature = record['main']['temp']
            humidity = record['main']['humidity']
            feels_like = record['main']['feels_like']
            return \
                f'{time}: {description}, {temperature:.1f} degrees F, {humidity:.0f}% humidity, ' + \
                f'feels like {feels_like:.1f} degrees F'
        except KeyError:
            return '[invalid forecast record]'
    
    
    class Record(Label):
        pass
    
    
    class Records(BoxLayout):
        records = ListProperty([])
    
        def rebuild(self):
            self.clear_widgets()
            for record in self.records:
                self.add_widget(Record(text=record))
    
        def on_records(self, _, __):
            self.rebuild()
    
    
    class RestApp(App):
        records = ListProperty([])
    
        def load_records(self):
            self.records = []
            connection = RESTConnection('api.openweathermap.org', 443, '/data/2.5')
            connection.send_request(
                'weather',
                {
                    'appid': API_KEY,
                    'lat': UNL_LATITUDE,
                    'lon': UNL_LONGITUDE,
                    'units': UNITS,
                },
                None,
                self.on_records_loaded,
                self.on_records_not_loaded,
                self.on_records_not_loaded
            )
    
        def on_records_loaded(self, _, response):
            self.records = [format_forecast_record(response)]
    
        def on_records_not_loaded(self, _, error):
            self.records = ['[Failed to load records]']
            Logger.error(f'{self.__class__.__name__}: {error}')
    
    
    if __name__ == '__main__':
        app = RestApp()
        app.run()