Как написать на питоне приложение погоды

от admin

Forecast Weather using Python

Weather is the mix of events that happen each day in our atmosphere and is different in different parts of the world and changes over minutes, hours, days, and weeks. Rain and dull clouds, windy blue skies, cold snow, and sticky heat are very different conditions, yet they are all-weather. According to the Wikipedia definition:

Weather is the state of the atmosphere.

In this blog post, we will learn how to forecast weather details. We will see the implementation in Python with hardly a few lines of code.

Check out the Repository for Ultimate Resource in python. Drop a star if you find it useful! Got anything to add? Open a PR on the same!

You can refer to my YouTube video Tutorial to see a working tutorial for better understanding and a step-by-step guide of the same.

What will be covered in this Blog

Let’s get started!

What is wttr?

wttr — the right way to check the weather!

wttr.in is a console-oriented weather forecast service that supports various information representation methods like terminal-oriented ANSI-sequences for console HTTP clients (curl, httpie, or wget), HTML for web browsers, or PNG for graphical viewers.

wttr.in uses wego for visualization and various data sources for weather forecast information.

If you wish to know more about it, you can refer to wttr’s GitHub Repo.

Module Used: requests Module:

Requests is a simple, yet elegant HTTP library. It allows you to send HTTP/1.1 requests extremely easily. Requests officially support Python 2.7 & 3.5+.

If you wish to know more about it, you can refer to Requests Module Documentation.

Now that you are familiar with Requests Module basics and have acquired basic knowledge of wttr, we can move forward to the coding section.

Time to Code!

You can find all the code in my GitHub Repository. Drop a star if you find it useful.

In order to access the Python library, you need to install it into your Python environment

Now, we need to import the package into our python script. Use the following command to do so.

Now that we have imported the library using the command import requests , let's proceed.

Let’s ask the user to input the city name for which he/she wishes to fetch the weather details.

You can also hard-code the value if you will only check for yourself.

Now, let’s display a simple message.

Let’s define the URL, We will make use of format to pass city as a parameter here.

It’s time to make use of the requests module.

Our resultant data is stored in res . We will make use of the text method to extract our desired weather details and let's display the result.

This is how the Weather Forecast will look like:

Isn’t it beautiful? And with that, it’s a wrap! I hope you found the article useful! Share in the comments below. I create content about Career, Blogging, Programming, and Productivity, If this is something that interests you, please share the article with your friends and connections. You can also subscribe to my newsletter to get updates every time I write something!

Thank you for reading, If you have reached so far, please like the article, It will encourage me to write more such articles. Do share your valuable suggestions, I appreciate your honest feedback!

I would strongly recommend you to Check out the YouTube video of the same and don’t forget to subscribe to my Channel. I would love to connect with you at Twitter | LinkedIn.

Узнаем текущую погоду и прогноз простеньким скриптом на Python’е

На Хабре есть интересная статья о том, как энтузиасты делают погоду. Энтузиасты делают, а мы воспользуемся плодами их трудов — получим эту самую погоду от OpenWeatherMap.org скриптом на Python’е.

Для получения доступа к сервису погоды придется пройти несложную процедуру регистрации на сайте OpenWeatherMap.org. Сформируем и отправим запрос, разберем ответный пакет в формате JSON, и получим текущую температуру с описанием состояния погоды.

Зарегистрироваться на openweathermap.org совсем несложно, а остальное сделать будет ещё проще.

Регистрация нужна для получения идентифицирующей пользователя строки App Id, состоящей из набора букв и цифр (похоже — только из шестнадцатеричных цифр). Такого вида:
«6d8e495ca73d5bbc1d6bf8ebd52c4». После регистрации нужно зайти в личный кабинет и взять App Id, который там называется «API key».

Формирование строки запроса

Сначала попытаемся найти интересующий нас город в их базе. Строка запроса должна быть примерно такая:

В запросе нужно указать нужный город (вместо «Petersburg») и свой App Id (вместо «6d8e495ca73d5bbc1d6bf8ebd52c4». Можно уточнить запрос, указав идентификатор страны после названия города через запятую. Например, так:

Собственно запросная строка будет сформирована самой библиотекой requests в функции get, которую используем для отправки запроса:

Проверка наличия в базе информации о нужном населенном пункте

План такой. В ответ на сформированный запрос получаем пакет в формате JSON. Разбираем пакет и получаем нужные значения по названиям полей.

Запомним числовой идентификатор города city_id для последующего запроса, потому что поставщики сервиса рекомендовали делать запрос не по имени, а по идентификатору.
В ответе может оказаться несколько городов, соответствующих нашему запросу. Кстати, если в запросе указать “Moscow” и убрать страну из строки приведенного в примере запроса, то гарантированно получим несколько строк в списке cities:

Получение информации о текущей погоде

Осталось только получить искомую информацию о погоде. Если нас не интересуют имперские единицы измерения, то в запросе указываем, что желаем получить метрические единицы: «units=metric». Если описание погоды нужно получить на русском, то указываем «lang=ru».

Если верить сервису, сейчас (14.11.2016 в 23:20) в Москве:

Прогноз на 5 дней

Получим такой вывод:
2016-11-24 15:00 -1 7 м/с ЮЗ пасмурно
2016-11-24 18:00 +2 7 м/с З легкий дождь
2016-11-24 21:00 +2 7 м/с З легкий дождь
2016-11-25 00:00 -0 7 м/с З ясно
2016-11-25 03:00 +0 7 м/с З небольшой снегопад
2016-11-25 06:00 -0 6 м/с СЗ слегка облачно
.

Скачать owm-request.py. Чтобы этот скрипт заработал, нужно в первой строке ввести Ваш «API key», полученный при регистрации на OpenWeatherMap.org.
Командная строка, например, такая:
$python owm-request.py Moscow,RU

На сайте OpenWeatherMap есть ещё масса интересного — получение информации по географическим координатам, архив погоды, информация с конкретных метеостанций. Описание всех доступных сервисов можно посмотреть здесь http://openweathermap.org/api
Для работы на Python’е с OpenWeatherMap существует специализированная библиотека pyowm.

Помимо OpenWeatherMap есть другие сайты, предоставляющие аналогичную информацию. Например, WorldWeatherOnline. Доступные API можно посмотреть здесь. Регистрация нужна. Есть библиотека на Python’е: pywwo.

Читать:
Компьютер включается не с первого раза в чем причина

Python TKinter / Создание GUI приложения для отслеживания погоды

Python позволяет создавать большой спектр приложений. В статье мы познакомимся с библиотекой TKinter и на её основе создадим приложение с дизайном для отслеживания погоды.

Информация про TKinter

Tkinter в списке библиотек не является лидером, но он явно заслуживает внимания благодаря своей простоте и возможностям что он предоставляет.

Библиотека является «open source» проектом, а также, что приятно, так это то, что написана она была никем другим как Стином Лумхольтом и Гвидо ван Россумом, на секундочку автором языка Питон.

Библиотека позволяет создавать графический интерфейс для ваших программ. Программы на ней могут содержать текстовые поля, кнопки, надписи, картинки и многие другие элементы.

Библиотека является встроенной, поэтому её не требуется дополнительно устанавливать в проект.

Создание проекта

Ниже представлен код готового приложения на TKinter. Если нужно больше информации, то просмотрите обучающее видео в конце этой статьи.

Видео на эту тему

Детальный разбор TKinter вы можете просмотреть на видео ниже. В видеоуроке показан полный разбор библиотеки и её возможностей.

Дополнительный курс

На нашем сайте также есть углубленный курс по изучению языка Питон . В ходе огромной программы вы изучите не только язык Питон, но также научитесь создавать веб сайты за счёт веб технологий и фреймворка Джанго. За курс вы изучите массу нового и к концу программы будете уметь работать с языком Питон, создавать на нём полноценные ПК приложения на основе библиотеки Kivy, а также создавать веб сайты на основе библиотеки Джанго.

Більше цікавих новин

Разработчик-полиглот: зачем знать несколько языков программирования?Разработчик-полиглот: зачем знать несколько языков программирования?
Как зарабатывать 24 000 $ в месяц на фрилансе?Как зарабатывать 24 000 $ в месяц на фрилансе?
Как с помощью JavaScript определить IP адрес пользователя?Как с помощью JavaScript определить IP адрес пользователя?
Самые интересные TED-видео о Data ScienceСамые интересные TED-видео о Data Science

Weather App in Python | Tkinter – GUI

GUI Based Weather App In Python

In this tutorial, you will learn about how to create a GUI Weather App in Python. It uses Open Weather Map API to fetch the latest weather information of cities and places around the globe. Also, we will be implementing the weather app with GUI (Graphical User Interface) rather than the traditional boring ways, which are widely available, showing output in CLI(Command Line Interface).

Code for Weather App in Python – GUI

Without further ado, let’s get right into the code setup for creating our GUI weather app in Python

1. Install and Import Tkinter

We begin with installing the required libraries using the pip package manager. Enter the below commands in your command line or terminal to install the modules.

We need to install:

    : to fetch data from API : to make our Weather app GUI (Graphical User Interface) based. : to change the time from API to a different format

After installing the required libraries from the terminal, we now move to our Python file to code. We start with importing the libraries as:

2. Initialize the Tkinter Window

As a next step, we initialize our GUI window using the Tkinter module.

3. OpenWeatherMap API

In our code, we will be using Open Weather API (free tier) to get the current weather information which is accurate and latest.

  • To do so, go to OpenWeatherMap website and create an account.
  • After creating your account, go to profile and then “My API keys“.
  • This will open a webpage for your API Key, as shown below, copy it for later use in code in the next step.

Open Weather Api

Open Weather Map API

4. Weather Function

Here, comes the part where we add functionality to our code. This part is the most crucial in getting correct weather information, as this involves fetching data from the API and displaying it in an accurate format.

We code the most important function of this code, which is for displaying weather, we do so as in the code:

As a final step to adding functionality, we add a function to change the time format, this function checks for the local time as compared to the UTC(Universal Time Coordinated) in which the API gives the output to the time format as per our location. Ex. UTC to IST.

5. Coding the GUI (frontend elements)

We now start to code the elements as per the GUI, for heading, text, labels, buttons, etc.

To start with, we code the text field for the City Name we want the weather for, along with the label to indicate so:

  • We use the Labelmethod to generate a label of text to indicate the purpose of the input field for city name.
  • Entrymethod is used to make an entry field for input of city name, to check its weather.
  • The textvaraible widget is used to store the inputted value, in the variable named: city_value
  • Other than these widgets we have also applied some styling to our code, by font size, color, etc.

We code a Check Weather Button, on which we click to check the weather of the user inputted city:

  • We give our button some styling, along with the name – ‘Check Weather’. We use the ‘command‘ widget, which shows what function (here, showWeather function) would run on the click (key press) of the button, as coded in the previous step.

After adding this, we add the output elements in our code. The elements on which our Weather information would be displayed.

  • Yet again, we add a label to title our result in the following text box
  • To display the output we use a text field , which gets its value, every time the “Check Weather” button is pressed. This envokes the function to check weather info fetched from the API after processing, [output from the showWeather function]

On execution of our code, the Tkinter displays this as output:

Weather App Frontend In Python

Weather App Frontend In Python

Final Code for GUI Weather App in Python

The Output of the GUI based Weather App is shown below:

Output for Weather App

Conclusion

That’s it for the tutorial. Hope you have learned well how to make a Weather App in Python and that too with a level up by coding an Interface Based script along with API call (Open Weather Map) and Tkinter.

Похожие статьи