|
| 1 | +from urllib.request import Request, urlopen |
| 2 | + |
| 3 | +from rich.text import Text |
| 4 | + |
| 5 | +from textual import work |
| 6 | +from textual.app import App, ComposeResult |
| 7 | +from textual.containers import VerticalScroll |
| 8 | +from textual.widgets import Input, Static |
| 9 | +from textual.worker import Worker, get_current_worker |
| 10 | + |
| 11 | + |
| 12 | +class WeatherApp(App): |
| 13 | + """App to display the current weather.""" |
| 14 | + |
| 15 | + CSS_PATH = "weather.css" |
| 16 | + |
| 17 | + def compose(self) -> ComposeResult: |
| 18 | + yield Input(placeholder="Enter a City") |
| 19 | + with VerticalScroll(id="weather-container"): |
| 20 | + yield Static(id="weather") |
| 21 | + |
| 22 | + async def on_input_changed(self, message: Input.Changed) -> None: |
| 23 | + """Called when the input changes""" |
| 24 | + self.update_weather(message.value) |
| 25 | + |
| 26 | + @work(exclusive=True) |
| 27 | + def update_weather(self, city: str) -> None: |
| 28 | + """Update the weather for the given city.""" |
| 29 | + weather_widget = self.query_one("#weather", Static) |
| 30 | + worker = get_current_worker() |
| 31 | + if city: |
| 32 | + # Query the network API |
| 33 | + url = f"https://wttr.in/{city}" |
| 34 | + request = Request(url) |
| 35 | + request.add_header("User-agent", "CURL") |
| 36 | + response_text = urlopen(request).read().decode("utf-8") |
| 37 | + weather = Text.from_ansi(response_text) |
| 38 | + if not worker.is_cancelled: |
| 39 | + self.call_from_thread(weather_widget.update, weather) |
| 40 | + else: |
| 41 | + # No city, so just blank out the weather |
| 42 | + if not worker.is_cancelled: |
| 43 | + self.call_from_thread(weather_widget.update, "") |
| 44 | + |
| 45 | + def on_worker_state_changed(self, event: Worker.StateChanged) -> None: |
| 46 | + """Called when the worker state changes.""" |
| 47 | + self.log(event) |
| 48 | + |
| 49 | + |
| 50 | +if __name__ == "__main__": |
| 51 | + app = WeatherApp() |
| 52 | + app.run() |
0 commit comments