Weather Forecaste System
Weather Forecaste System
INTRODUCTION
1.1 What is Live Weather Forecast System
Live Weather forecasting is the application of science and technology to predict the conditions of
the atmosphere for a given location and time. Human beings have attempted to predict
the weather informally for millennia and formally since the 19th century. Weather forecasts are
made by collecting quantitative data about the current state of the atmosphere at a given place
and using meteorology to project how the atmosphere will change. Once a human-only endeavor
based mainly upon changes in barometric pressure, current weather conditions, and sky condition
or cloud cover, weather forecasting now relies on computer-based models that take many
atmospheric factors into account. Human input is still required to pick the best possible forecast
model to base the forecast upon, which involves pattern recognition skills, teleconnections,
knowledge of model performance, and knowledge of model biases. The inaccuracy of
forecasting is due to the chaotic nature of the atmosphere, the massive computational power
required to solve the equations that describe the atmosphere, the error involved in measuring the
initial conditions, and an incomplete understanding of atmospheric processes. Hence, forecasts
become less accurate as the difference between current time and the time for which the forecast
is being made (the range of the forecast) increases. The use of ensembles and model consensus
help narrow the error and pick the most likely outcome.There are a variety of end uses to weather
forecasts. Weather warnings are important forecasts because they are used to protect life and
property. Forecasts based on temperature and precipitation are important to agriculture, and
therefore to traders within commodity markets. Temperature forecasts are used by utility
companies to estimate demand over coming days. On an everyday basis, people use weather
forecasts to determine what to wear on a given day. Since outdoor activities are severely
curtailed by heavy rain, snow and wind chill, forecasts can be used to plan activities around these
events, and to plan ahead and survive them. In 2009, the US spent $5.1 billion on weather
forecasting.Weather forecasts are made by collecting as much data as possible about the current
state of the atmosphere (particularly the temperature, humidity and wind) and using
understanding of atmospheric processes (through meteorology) to determine how the atmosphere
evolves in the future. However, the chaotic nature of the atmosphere and incomplete
1
understanding of the processes mean that forecasts become less accurate as the range of the
forecast increases. Traditional observations made at the surface of atmospheric pressure,
temperature, wind speed, wind direction, humidity, precipitation are collected routinely from
trained observers, automatic weather stations or buoys. During the data assimilation process,
information gained from the observations is used in conjunction with a numerical model's most
recent forecast for the time that observations were made to produce the meteorological analysis.
Numerical weather prediction models are computer simulations of the atmosphere. They take the
analysis as the starting point and evolve the state of the atmosphere forward in time using
understanding of physics and fluid dynamics. The complicated equations which govern how the
state of a fluid changes with time require supercomputers to solve them. The output from the
model provides the basis of the weather forecast.
1.2 Objective
To build a prototype model of “Live Weather Forecast”, for use by individuals. The project
involves live forecast of weather like Temperature or any who wants to know any information of
current location i.e.latitude, longitude, visibility, The Project is based
On Django that combines all the templates directories from the various apps.
Mnl..k[] On HTML we'll use for the template.
OnOpen Weather Map API This will allow us to get the actual weather for any cities that we
add in our app.
On Python library requests to get the actual weather data.
On URL using the city and get the JSON representation of that city.
2
1.4 Proposed System
This project is to produce an interactive web application that could be used to display live and
future forecasting information on the weather. Incorporated into the application were webcams
located at the user’s specified location, so giving visual data of the actual area. Initial
background reading focused on which mapping system to use, in combination with a particular
weather data source. After looking at several options, the Django framework was used with The
Weather Channel’s API, mainly due to Django’s rapid setup and because of the availability of
the Weather Channel in not just the UK but worldwide. After researching methodologies, the
decision made was to follow an adapted version of the Agile Unified Process. The adaptation
was based on the project being managed and run by one person, so therefore slightly simplifying
the steps. User involvement was important at the testing and evaluation stages as the project is
fundamentally aimed at end-users, so ensuring that other people not involved in the project were
given a chance to test the system’s robustness, whilst giving a chance for feedback for fixes or
changes. Usability was a big issue in the project’s design and implementation and as such several
factors were taken into account such as ensuring the application is compliant and will run well
on older or more restricted browsers.
3
Chapter 2
BACKGROUND OF PROJECT
2.1 Django
Django is a web development framework that assists in building and maintaining web
applications. Django helps reduce repetitive tasks making the development process an easy and
time saving. Django is a high-level Python web framework that encourages rapid development
and clean, pragmatic design. Django makes it easier to build better web apps quickly and with
less code.
History of Django
2003 − Started by Adrian Holovaty and Simon Willison as an internal project at the
Lawrence Journal-World newspaper.
2005 − Released July 2005 and named it Django, after the jazz guitarist Django Reinhardt.
2005 − Mature enough to handle several high-traffic sites.
Current − Django is now an open source project with contributors across the world.
4
2.2 Python
Python is a popular programming language. It was created in 1991 by Guido van Rossum. It is
used at number of places as:
Python can be used on a server to create web applications.
Python can be used alongside software to create workflows.
Python can connect to database systems. It can also read and modify files.
Python can be used to handle big data and perform complex mathematics.
Python can be used for rapid prototyping, or for production-ready software development.
2.2.1 Why Python
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines than some other
programming languages.
Python runs on an interpreter system, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.
Python can be treated in a procedural way, an object-orientated way or a functional way.
5
CHAPTER 3
TECHNOLOGIES USED
3.1 PYTHON
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming
language. It was created by Guido van Rossum during 1985- 1990. Like Perl, Python source
code is also available under the GNU General Public License (GPL). This tutorial gives enough
understanding on Python programming language. It is used for:
web development (server-side),
software development,
mathematics,
system scripting.
3.2 JSON
6
JSON is a text format that is completely language independent but uses conventions that are
familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript,
Perl, Python, and many others. These properties make JSON an ideal data-interchange
language.JSON is built on two structures:
3.3 HTML
HTML Stands for Hypertext Markup Language.
Hypertext is ordinary text that has been dressed up with extra features, such as formatting,
images, multimedia, and links to other documents. Markup is the process of taking ordinary text
and adding extra symbols. Each of the symbols used for markup in html is a common that tells a
browser how to display the text. HTML is the predominant markup language for creation of web
pages. It provides a means to describe the structure of text based information in a document- by
denoting certain text as heading, paragraph, and lists and so on- and to supplement that text with
interactive forms, embedded images, and other objects. Html is written in the form of labels
(known as tags), surrounded by less than (<) and greater than (>) sign. Html can also describe, to
some degree, the appearance and semantics of a document, and can include embedded scripting
language code which can affect the behavior of web browsers and other HTML process. HTML
is also used to refer to content to the MIME type text/html or even more broadly as a generic
term for HTML whether in its XML-descended form or its form descended directly from SGML.
TIM Burners Lee created the original HTML on a next cube workstation using the next STEP
development environment. At the time, HTML was not a specification, but a collection of
loosely defined elements to solve immediate problems: the communication and dissemination of
ongoing research between Lee burners and his colleagues. His solution later combined with the
emerging international and public internet to garner worldwide attention. The original design of
HTML was simple. The first publicly availabledescription of HTML was a document called
7
HTML tags. The document describes 22 elements that made up the initial design of HTML.
Thirteen of these elements still exist in HTML 4.
3.4 JAVASCRIPT
JavaScript often abbreviated as JS, is a high level, interpreted programming language. It is a
language which is also characterized as dynamic, weakly typed, prototype-based and multi-
paradigm.Alongside HTML and CSS, JavaScript is one of the three core technologies of
the World Wide Web. JavaScript enables interactive web pages and thus is an essential part
of web applications. The vast majority of websites use it, and all major web browsers have a
dedicated JavaScript engine to execute it. As a multi-paradigm language, JavaScript supports
event-driven, functional, extensional, and imperative (including object-oriented and prototype-
based) programming styles. It has an API for working with text, arrays, dates, regular
expressions, and basic manipulation of the DOM, but the language itself does not include
any I/O, such as networking, storage, or graphics facilities, relying for these upon the host
environment in which it is embedded.
Initially only implemented client-side in web browsers, JavaScript engines are now embedded in
many other types of host software, including server-side in web servers and databases, and in
non-web programs such as word processors and PDFsoftware, and in runtime environments that
make JavaScript available for writing mobile and desktop applications, including desktop
widgets.Although there are strong outward similarities between JavaScript and Java, including
language name, syntax, and respective standard libraries, the two languages are distinct and
differ greatly in design; JavaScript was influenced by programming languages such
as Self and Scheme.
8
Figure-3.1 Open Weather Map
9
CHAPTER 4
Software requirement
10
CHAPTER-5
IMPLEMENTATION
In this project I built a simple Django app that forecast the current weather for various cities.
To get the current weather data, we use the Open Weather Map API.
Installation
The Admin Dashboard
Creating the App
Adding the Template and View
Using the Weather API
Displaying the Data in the Template
Creating the Form
Conclusion
Even though the app is simple, we'll work with a database and create a form, so the concepts
used here are applicable to more complicated projects. The code in this article was written with
Python 3 and Django 2.0, so. In this Project I have used Django 1.X, but you'll see the only
difference is in how URLs are defined.Here's what our app is going to look like when we're
done.
Figure-5.1WeatherForecastSystem
You can see a live demo of the app on Python Anywhere.
11
5.1 Installation
Installing Django is like installing any other Python library: you can start a virtual environment
and run pip to install Django, or you can do what I do and create a project directory, run pipenv
and then activate the pipenv shell. Either method works, but for this article I'll be using pipenv.
Pipenv install Django This will install the latest version of Django for you. At the time of
writing this article, Django is on version 2.0.4.Once you have Django installed, create and
navigate to a directory for this project if you haven't already. Once there, you can run the
startproject command that Django gives you to generate the project Django-admin start project
the _weatherDjango should have created a few new files in your directory. Let's try starting up
our development server. To do that, navigate to the new directory and use manage.py to run the
runserver command in your terminal:
Cd sumit
cd manage.py runserver If you look at your terminal, you should see the URL for your app. By
default it should be 127.0.0.1:8000.
Open up your browser and go to that URL 127.0.0.1:8000 If you see that, you know you've set
up Django correctly. You definitely should see it because we haven't even tried modifying the
code yet.Top of Form Bottom of Form
12
5.2 Creating the App
In Django, you can separate functionality in your project by using apps. I think app is a
confusing name because we usually refer to an app as being the entire project, but in the case of
Django, app refers to a specific piece of functionality in your project. For example, if you look at
the settings.py file, you'll see the INSTALLED_APPS list. The first of the installed apps,
django.contrib.admin is what we just used. It handles all the admin functionality and nothing
else. Another app in our project by default are things like auth, which allowed us to log into our
admin dashboard. In our case, we need to create a new app to handle everything related to
showing the weather. To create that app, stop the server with CTRL+C and run: python
manage.py startapp weather By running startapp, Django has added a new directory and more
files to our project. With the latest files generated, let's create a new file called urls.py in our
app directory.
#the_weather/weather/urls.py
fromdjango. urlsimport path
url patterns =[
]
This file is similar to the urls.py in our the_weather directory. The difference is that this urls.py
file contains all the URLs that are relevant to the app itself. We're not specifying a URL yet, but
we can set up the project to recognize our app and route any URLs specific to our app to the app
urls.py file. First, go to the INSTALLED_APPS list and add this app to the list.
#the_weather/the_weather/settings.py
...
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Sumit',
13
]
...
This lets Django know we want to use the weather app in our project. By doing this, Django will
know where to look for migrations and the URLs. Next, we need to modify the original urls.py to
point to our app urls.py file. To do that, we add a line under the existing path for the admin
dashboard. We also need to import 'include' so we can point to our app urls.py file.
#the_weather/the_weather/urls.py
fromdjango.contribimport admin
fromdjango.urlsimport path, include
urlpatterns=[
path('admin/',admin.site.urls),
path('', include('sumit.urls')),
]
The empty string means that we won't use an endpoint for the entry point to our app. Instead
we'll let the app handle any specific endpoints. We could have easily put something like
path('weather/', ...), which would have meant we would have to type 127.0.0.1:8000/weather/
to get anything associated with our weather app. But since our project is simple, we won't be
doing that here.
14
directory, create a new file called index.html. This will be our main template. Here's the HTML
we'll use for the template.
<!--the_weather/weather/templates/weather/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>What's the weather like?</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.2/css/bulma.css" />
</head>
<body>
<section class="hero is-primary">
<div class="hero-body">
<div class="container">
<h1 class="title">
What's the weather like?
</h1>
</div>
</div>
</section>
<section class="section">
<div class="container">
<div class="columns">
<div class="column is-offset-4 is-4">
<form method="POST">
<div class="field has-addons">
<div class="control is-expanded">
<input class="input" type="text" placeholder="City Name">
</div>
<div class="control">
<button class="button is-info">
Add City
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</section>
<section class="section">
<div class="container">
<div class="columns">
15
<div class="column is-offset-4 is-4">
<div class="box">
<article class="media">
<div class="media-left">
<figure class="image is-50x50">
<imgsrc="http://openweathermap.org/img/w/10d.png" alt="Image">
</figure>
</div>
<div class="media-content">
<div class="content">
<p>
<span class="title">Manesar</span>
<br>
<span class="subtitle">29° F</span>
<br> thunderstorm with heavy rain
</p>
</div>
</div>
</article>
</div>
</div>
</div>
</div>
</section>
<footer class="footer">
</footer>
</body>
</html>
Now that we have our template created, let's create a view and URL combination so we can
actually see this in our app.Views in Django are either functions or classes. In our case since
we're creating a simple view, we'll create a function. Add this function to your views.py:
#the_weather/weather/views.py
fromdjango.shortcutsimport render
defindex(request):
return render(request,'weather/index.html')#returns the index.html template
We're naming our view 'index' because it will be at the index of our app, which is the root URL.
To have the template render, we return request, which is necessary for the render function, and
the name of the template file we want to render, in this case weather/index.html. Let's add the
URL that will send the request to this view. In the urls.py for the app, update the url patterns list.
#the_weather/weather/urls.py
16
fromdjango.urlsimport path
from.import views
urlpatterns=[
path('',views.index),#the path for our index view
]
This allows us to reference the view we just created. Django is going to match any URL without
an endpoint and route it to the view function we created. Go back to your project root, start the
server, and go to 127.0.0.1:8000 again. python manage.py runserver .What we see now is just the
result of the HTML you have in index.html file. You'll see an input to add a city and the weather
for Las Vegas. However, the form doesn't work and the weather is just a placeholder, but don't
worry, because we'll be creating those for this app.
Figure-5.3 Dashboard
The one endpoint we'll use is below, so you can see the actual data that gets returned by
modifying the following URL with your API key and navigating to the URL in your browser.It
may take a few minutes for your API key to become active, so if it doesn't work at first, try again
in after a few minutes.
17
http://api.openweathermap.org/data/2.5/weather?q=las%20vegas&units=imperial&appid=YOUR
_APP_KEY
Figure-5.4 API Key
With that, let's add in a request to get the data into our app. First, we'll need to install requests so
we can call the API from inside our app. Pipenv install requestsLet's update our index view to
send a request to the URL we have.
#the_weather/weather/views.py
fromdjango.shortcutsimport render
import requests
defindex(request):
url='http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=YOUR_API
_KEY'
city='Manesar'
city_weather=requests.get(url.format(city)).json()#request the API data and convert the JSON to
Python data types
return render(request,'weather/index.html')
#returns the index.html template
you start your server again and reload the page, you'll see the data get printed to your console
With those three lines, we're adding the URL that will send a request to. We'll make the part for
the city a placeholder for when we allow users to add their own cities.For now we'll set the city
to be Las Vegas, but later this will be set to the cities from the database. Finally, we'll send the
request to the URL using the city and get the JSON representation of that city. If we print that to
the console we can see the same data we saw when we put the URL in our address bar.If.
18
return render(request,'weather/index.html')#returns the index.html template
Now that we all the information we want, we can pass that to the template. To pass it to the
template, we'll create a variable called context. This will be a dictionary that allows us to use its
values inside of the template.
#the_weather/weather/views.py
defindex(request):
...context={'weather': weather}
return render(request,'weather/index.html', context)
#returns the index.html template
And then in render, we'll add the context as the third argument. With the weather data added
inside of context, let's go to the template to add the data. Inside of the template, all we need to do
is modify the HTML to use variables instead of the values I typed in. Variables will use {{ }}
tags, and they will reference anything inside of your context dictionary. Note that Django
converts dictionary keys so you can only access them using dot notation. For example,
weather.city will give us the city name. We don't use weather['city'] like we would in Python.
Find the box div, and update it to this:
<!--the_sumitOl/sumit/templates/sumit/index.html -->
<div class="box">
<article class="media">
<div class="media-left">
<figure class="image is-50x50">
<imgsrc="http://openweathermap.org/img/w/{{ weather.icon }}.png" alt="Image">
</figure>
</div>
<div class="media-content">
<div class="content">
<p>
<span class="title">{{ sumit.city }}</span>
<br>
<span class="subtitle">{{ sumit.temperature }}° F</span>
<br> {{ weather.description }}
</p>
</div>
</div>
</article>
</div>
With all the variables replaced, we should now see the current weather for our city
19
Figure-5.4 Weather Forecast System
Great! Now we can see the weather for one city, but we had to hard code the city. What we want
to do now is pull from the database and show the cities that are in our database. To do that, we'll
create a table in our database to hold the cities that we want to know the weather for. We'll create
a model for this.Go to the models.py in your weather app, and add the following:
#the_weather/weather/models.py
fromdjango.dbimport models
classCity(models.Model):
name=models.CharField(max_length=25)
def__str__(self):#show the actual city name on the dashboard
return self.name
classMeta:
#show the plural of city as cities instead of citys
verbose_name_plural='cities'
This will create a table in our database that will have a column called name, which is the name of
the city. This city will be a charfield, which is just a string. To get these changes in the database,
we have to run make migrations to generate the code to update the database and migrate to apply
those changes. So let's do that now.
python manage.py makemigrations
python manage.py migrate
20
We need to make it to where we can see this model on our admin dashboard. To do that, we
need to register it in our admin.py file.
#the_weather/weather/admin.py
fromdjango.contribimport admin
from.models import City
admin.site.register(City)
You'll see the city as an option on the admin dashboard. We can then go into the admin
dashboard and add some cities. I'll start with One city ‘Manesar’ With the entries in the database,
we need to query these entries in our view. Start by importing the City model and then querying
that model for all objects.
#the_weather/weather/views.py
fromdjango.shortcutsimport render
import requests
from.models import City
#the_weather/weather/views.py
defindex(request):
url='http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=YOUR_APP
_KEY'
cities=City.objects.all()#return all the cities in the database
...
Since we have the list of cities, we want to loop over them and get the weather for each one and
add it to a list that will eventually be passed to the template. This will just a variation of what we
did in the first case. The other difference is we are looping and appending each dictionary to a
list. We'll remove the original city variable in favor a city variable in the loop.
#the_weather/weather/views.py
defindex(request):
weather_data=[]
for city in cities:
city_weather=requests.get(url.format(city)).json()#request the API data and convert the JSON to
Python data types
weather={
21
'city': city,
'temperature':city_weather['main']['temp'],
'description':city_weather['weather'][0]['description'],
'icon':city_weather['weather'][0]['icon']
}
weather_data.append(weather)#add the data for the current city into our list
context={'weather_data':weather_data}
Cool, so we have the data. Now let's update the context to pass this list instead of a single
dictionary.
#the_weather/weather/views.py
context={'sumit_data':sumit_data}
...
Next, inside of the template, we need to loop over this list and generate the HTML for each city
in the list. To do this, we can put a for loop around the HTML that generates a single box for the
city.
<!--the_weather/weather/index.html -->
<div class="column is-offset-4 is-4">
{% for weather in weather_data %}
<div class="box">
<article class="media">
<div class="media-left">
<figure class="image is-50x50">
<imgsrc="http://openweathermap.org/img/w/{{ weather.icon }}.png" alt="Image">
</figure>
</div>
<div class="media-content">
<div class="content">
<p>
<span class="title">{{ weather.city }}</span>
<br>
22
<span class="subtitle">{{ weather.temperature }}° F</span>
<br> {{ weather.description }}
</p>
</div>
</div>
</article>
</div>
{% endfor %}
</div>
Awesome! Now we can see the data for all the cities we have in the database.
23
defindex(request):
...form=CityForm()
weather_data=[]
...context={'weather_data':weather_data,'form': form}
Now in the template, let's update the form section to use the form from our view and a
csrf_token, which is necessary for POST requests in Django.
<form method="POST">
{% csrf_token %}
<div class="field has-addons">
<div class="control is-expanded"
{{ form.name }}
</div>
<div class="control">
<button class="button is-info">
Add City
</button>
</div>
</div>
</form>
With the form in our HTML working, we now need to handle the form data as it comes in. For
that, we'll create an if block checking for a POST request. We need to add the check for the type
of request before we start grabbing the weather data so we immediately get the data for the city
we add.
#the_weather/weather/views.py
defindex(request):
cities=City.objects.all()#return all the cities in the database
url='http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=YOUR_APP
_KEY'
if request.method=='POST':# only true if form is submitted
form=CityForm(request.POST)# add actual request data to form for processing
form.save()# will validate and save if validate
form=CityForm()
...
By passing request.POST, we'll be able to validate the form data. Now you should be able to
type in the name of a city, click add, and see it show up. I'll add Delhi as the next city.
24
Figure-5.6 Weather Forecast of Delhi
When we drop out of the if block, the form will be recreated so we can add another city if we
choose. The rest of the code will behave in the same way. And that's it! We now have a way to
keep track of the weather for multiple cities in our app
25
Chapter 6
SCREEN SHOTS
26
Figure 6.2: Screenshot of Weather forecast
27
Figure-6.4 :Screenshot for Index.html
28
Figure 6.6: Screenshot for view.py
29
.
Figure-6.7 WeatherForecast
30
Chapter 7
CONCLUSION
In this project, we had to work with various parts of Django to get this working: views, models,
forms, and templates. We also had to use the Python library requests to get the actual weather
data. So even though the app is simple, you'll use many of the same concepts in apps with more
complexity. Weather plays a major role in our daily life, and without the meteorologist and
forecaster we would have difficulty planning our daily activities. As we can see, the weather is
not a simple subject like we may have been thinking. The study of weather phenomenon requires
the use of science, math, and different types of equipment and technology and data. Even with all
these equipment, data, and observation tools, the weather continues to be a topic to study because
it is constantly changing. Meteorologist and forecasters predict the weather and its possible
changes, but in reality, weather is still unpredictable. The two different types of forecasting
models, one of them based on finite differences, the other one based on the spectral method, are
currently competing as to which one of them yields more accurate forecasts for a given
computational cost. But at the end of the day, each model has its strengths and weaknesses; so
using both models side by side will probably give the best results.
In the future, weather forecasts will be even more accurate and more detailed than forecasts
nowadays. And who knows, maybe one day mathematicians will find a way to overcome the two
weeks forecasting limit, so that long-range forecasts can be produced.
31
REFERENCES
Web sites referred
www.openweathermapapi.com
https://docs.djangoproject.com/en/1.8/intro/tutorial01/
https://docs.python.org/3/tutorial/
https://github.com/topics/weather-api?l=python&o=asc&s=stars
32