How I Built a Weather App with Python Streamlit : Jonathan Okah

How I Built a Weather App with Python Streamlit
by: Jonathan Okah
blow post content copied from  Be on the Right Side of Change
click here to view original post


5/5 - (1 vote)

This is the final series of this three-part project tutorial in which I demonstrated how I created just one application using three Python frameworks.

In the first part, we learned how to design such applications using Django, a Python framework for designing complex web applications. In that first part, we also learned how to fetch weather data using an API, isolated the data we needed and have them displayed dynamically on template files.

The second part focuses on using the Flask framework to create the weather application. That was the first time I created projects using Flask. We also used the OpenWeatherMap API to get real-time weather data for a particular region.

If you haven’t gone through those projects, I recommend you do so. Of course, it is not a requirement before attempting this project.

In this third and final part, we will build the same weather application using, this time, the Streamlit Python framework. I save the best for the last. This tutorial is special and different from the previous two for the following reasons:

  1. It is short and simple;
  2. It does not require any protocol like we saw while using Django and Flask;
  3. We will be using a different API that comes with a Python package;
  4. Unlike the previous two project tutorials, our app will contain a 7-day weather forecast.

💡 Note: OpenWeatherMap also has a Python package and can make weather forecasts for the next day. Let us first demonstrate how to make forecasts using OpenWeatherMap before proceeding to the API we will use to create the Streamlit application.

Install the Python package using pip.

pip install pyown

Assuming you already have your API key, let’s get started. Import the pyown module and store your API key in a variable.

import pyown
key = 'your_api_key'

Enter your key into the OWM class that serves as an entry point into API clients.

owm = pyowm.OWM(key)

Next, use the weather_manager() method to create an instance to get weather data from OpenWeatherMap.

mgr = owm.weather_manager()

Then, get the weather at a specific location using weather_at_place() method.

obs = mgr.weather_at_place('Rome')

Now, all we need to do is to retrieve the weather class containing the weather data.

weather = obs.weather
weather.status

The result is a string containing the weather condition for that region. Of course, there are other things we can check such as wind, temperature and so on. Run dir(weather) on your Python shell to see some of them.

If we want to make a 6-day forecast, we follow the same way using forecast_at_place() method.

forecast = mgr.forecast_at_place('Lagos', '3h')

Then we loop over the forecast class to get the weather data every three hours for every six days

for weather in forecast.forecast:
    print(weather.detailed_status)

You can see that the OpenWeatherMap Python package make things very easy and shows more weather data than the two previous project we created. However, for this project tutorial, we will use WeatherBit Python package.

Head over to their website and create an account to get your API key.

Creating the Application

Just as I mentioned earlier, this application is going to be simple as the heavy work has already been done for us. All we need to do is to enter our API keys, city name, optional city-state, and the given country.

Then, the result will be fetched by the WeatherBit Python package and displayed on the Streamlit application.

from weatherbit.api import Api
import pandas as pd
import streamlit as st


st.title('A Seven-Day Weather Forecast App')
key = st.text_input('Enter key')
api = Api(key)


@st.cache_resource
def weather_forecast(city, state, country):
    api = Api(key)
    forecast = api.get_forecast(city=city, state=state, country=country)
    return forecast

left, right = st.columns(2)
city = left.text_input('Enter City')
state = right.text_input('Enter City State')
country = st.text_input('Enter Country')
op = st.selectbox('Make a choice', ['DataFrame', 'BarChart', 'LineChart'])
if st.button('Fetch'):
    forecast = weather_forecast(city, state, country)
    dates = []
    precips = []
    weather = []
    wind = []
    temp = []
    for day in forecast.get_series(['temp', 'precip', 'weather','wind_spd' ,'datetime']):
        dates.append(day['datetime'].date())
        temp.append(day['temp'])
        precips.append(day['precip'])
        weather.append(day['weather']['description'])
        wind.append(day['wind_spd'])
    df = pd.DataFrame({'Date': dates, 'Temp': temp, 'Precip': precips, 'Wind Speed': wind, 'Weather': weather})
    if op == 'DataFrame':
        st.dataframe(df)
    elif op == 'BarChart':
        st.bar_chart(df.Temp)
    else: 
        st.line_chart(df.Temp)

That’s all for the Streamlit weather application written in just a few lines of code. Let’s briefly explain what’s going on there.

After importing the required modules, we use the text_input() function to receive the key from the user and passes it to the API type that was imported. We still need more details from the user, the city, optional city state and the country.

Once we receive them, we pass them to the weather_forecast() function. We wrap the function with st.cache_resource decorator. This caches the data received from the API so that we can occasionally glance at the data or use it for the bar chart and line chart without having to make repeated API calls.

To organize the weather results suitable to be displayed on the Streamlit application, we perform a for loop. The result in each iteration is appended to a new list. We then pass them to a Pandas DataFrame.

One last information the application is requesting is for the user to decide what should be displayed. A Pandas DataFrame displaying weather prediction for the next 7 days, a bar chart or a line chart on temperature data will be displayed depending what is selected by the user.

Conclusion

This is how we completed this project series. We created a weather application using three Python frameworks: Django, Flask, and Streamlit.

Choose Django and Flask if you are creating a larger application and want to add a weather feature to it. Choose Streamlit if you are creating a single-page application and want to reduce the amount of code you have to write.

You can find the complete source code on GitHub and the app running on the cloud. I hope this project will help you in improving your Python skills.

💡 Recommended:


June 04, 2023 at 07:10PM
Click here for more details...

=============================
The original post is available in Be on the Right Side of Change by Jonathan Okah
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================

Salesforce