Simple Flask Weather Application

Introduction

What is Flask ?
  • A Web-Application Framework or Web Framework is the collection of modules and libraries.
  • It helps the developer to write applications without writing the low-level codes such as protocols, thread management, etc.
  • Flask is one such web-application framework and it is based on WSGI(Web Server Gateway Interface) toolkit and Jinja2 template engine.
  • It is an API of python that allows to build up web applications.

Getting started with our App

Setting up the Env :-
  • Install python

    Python 2.6 or higher is required for installation of the Flask.

  • Install pip

    Pip is a Package manager for python which we will use to load in modules/libraries into our environments.An example of one of these libraries is VirtualEnv which will help us keep our environments clean from other Libraries. It is somewhat similar to what we have in ubuntu ie yum or apt-get to be more familiar. You can try out pip help to learn more.

  • It is recommended to use virtual environment to keep your libraries/dependencies seperate for different projects. You can use the packages virtualenv and virtualenvwin-wrapper about which you can find more over the internet.
Requirements to be installed :-
  • pip install flask
  • pip install requests
Now let us start building our software.
I will explain the entire code step by step in the next tab and to understand the code more easily you can refer my git hub project, the link for which is provided at the end.

Weather App

First open a python file named weather.py in your virtual environment and import below modules as we will use them in our program.
    import requests
    from flask import Flask,redirect,url_for,render_template,request
flask is the framework here and Flask is a prototype used to create instances of the web application while the rest of the modules are specific to our app.
    app=Flask(__name__)
  • From above code fragment we create an instance of Flask class and assign it to our web application app.
  • __name__ is a special variable which gets the value "__main__" while executing the script.
  • We will talk more about "__main__" later.
    url='https://api.openweathermap.org/data/2.5/weather?q={}&appid=***Your API Key here***'
We have used openweather api to fetch the weather related details and display to end user and defined above url to be used in results function.
  • Now we will require two html pages, one to take user input of location name and second to display the fetched results related to temperature.
  • We will use home.html as our front page where we will take user input of location name.
    form action="result" method="POST"
    input type="text" placeholder="Enter Location..." name="loc"
  • At home page, we will need to design a form with an input text box and parameters as above.
  • result.html will simply display the output to the user.
    @app.route("/",methods=["POST","GET"])
    def home():
    if request.method=="POST":
        return redirect(url_for("result"))
    else:
        return render_template("home.html")
  • The url "/" is bound with the home() function i.e. whenever it is called, the output of home() is displayed accordingly.
  • methods parameter states that we have permitted only GET and POST methods.
  • Now as we have designed a form with POST method, when user enters input and clicks SUBMIT, we will redirect him to the url for results.
  • We will use the modules redirect and url_for which we imported earlier.
  • By default, the user will be on home page unless he clicks SUBMIT.
    @app.route("/result",methods=["POST","GET"])
    def result():
        city=request.form['loc']
        results=requests.get(url.format(city)).json()
        weather={
            'city':city,
            'country':results['sys']['country'],
            'temp':results['main']['temp'],
            'info':results['weather'][0]['description'],
            'icon':results['weather'][0]['icon']
        }
        print(weather)
        return render_template("result.html",weather=weather)
  • Now we will define url result with methods GET and POST as above.
  • We will use the request module to fetch the element from the form with name 'loc' i.e. the input city.
  • Lets use the requests module to get the temperature details from the url we defined earlier and store in results variable in json format.
  • The input city will replace the {} in our url variable.
  • Now the output results will contain a lot of data which we can filter and store in weather and also print it in out cmd console.
  • At last we will use the render_template module and pass weather to display the final result.
  • You can display your result from weather variable using the Jinja2 standards (refer result.html).
if __name__=="__main__":
    app.run()
  • The condition __name__ == "__main__" ensures that the run() method is called only when main.py is run as the main program.
  • The run() method will not be called if you import main.py in another Python module.
  • To understand more, this blog can be helpful.

Now we are good to run our app.

  • Just run your app by typing python weather.py in your cmd prompt.
  • By default, it will run on your localhost port 5000
  • Open it in your browser and check out your app.

Hope this tutorial was helpful. You can check out the live app, link for which is provided at the end.
Thanks !!
Check out the Github repo for this project !
Click here for the live weather application !