Blogger Widgets

Search This Blog

Wednesday, 12 December 2012

Weather App using Tornado


Tornado is a scalable, non-blocking web server and web application framework. It was developed by FriendFeed.The framework is distinct from most mainstream web server frameworks (and certainly most Python frameworks) 
because it is non-blocking and reasonably fast.

Starting with Tornado


import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")

application = tornado.web.Application([
    (r"/", MainHandler),
])

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

Run this code using python and go to http://www.localhost:8888 will print 
"Hello, world" in firefox.

How we have done it ? 

The problem is to create a weather app using tornado frame work.For this we need to fetch the live whether data.I'm using openwhethermap.org to fetch climate data. I'm uses urllib library to get weather data from the weather server. And converted it to dict format using ast module in python. Then filter the required data(Temperature, Humidity, Pressure) from dict. Up to this first section of the project is completed.

Now I want to create a template

I'm create template in html . Now we need to put weather data's  (Temperature , Humidity, Pressure) in template. For integrating this values I'm uses jinja2 .

Main code for weather app 

weather.py

'''
-----------------------------------------------------------------------------------------------------
Created on 12-Dec-2012
@author: unais

This is the main program for the weather app

weather server used : http://openweathermap.org/data/2.1/forecast/city?q=Kochin

Here urllib is used to fetch climate data from openweathermap.org

"jinja2" template engine is used to render html pages with tornado

Template is saved in /template/weather.html

we can give different city names in plase of "Palakkad" for getting weather datas of different citys
------------------------------------------------------------------------------------------------------
'''
import urllib2
import ast
import tornado.ioloop
import tornado.web
import jinja2
import os


jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__) + "/templates"))

def getWeatherCondition(city) :
    try :
        url = "http://openweathermap.org/data/2.1/forecast/city?q="
        url += city
        req = urllib2.Request(url)
        response=urllib2.urlopen(req)
    except Exception :
        print("Not a matched city")
    return response.read()

def print_weather(place):
    Data_str =  getWeatherCondition(place)
    Data = ast.literal_eval(Data_str) # converting string to dict type
    Temperature =  Data['list'][0]['main']['temp']
    Humidity    =  Data['list'][0]['main']['humidity']
    Pressure    =  Data['list'][0]['main']['pressure']
    Result      =  place , Temperature , Humidity , Pressure
    return Result
  
class MainHandler(tornado.web.RequestHandler):
    def get(self):
        weather_data = print_weather("Palakkad") # by changing the name we get the weather datas of different city's
        template_values = { 'place':weather_data[0], 'temperature': str(weather_data[1] -272.15), 'humidity': str(weather_data[2]), 'pressure': str(weather_data[3])}
        template = jinja_environment.get_template('weather.html')
        self.write(template.render(template_values))

application = tornado.web.Application([
    (r"/", MainHandler),
])

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
  

HTML code for template

<!DOCTYPE html>
<html>
<body>
<div style="width:450px;height:250px;border:1px solid #000;background-color:LightBlue;">
 <img border="0" src="sun.png" style="float:right; margin:20px 20px 15px 15px;border:0" alt=" " width="150" height="150">

<pre>

<font size="8"><b>  {{temperature}}<sup>o</sup>C</b> </font>

<font size= "4"><b>   Humidity : {{humidity}}%</font></b>
<font size= "4"><b>   Pressure : {{pressure}} mbar</font></b>   
</pre>
</div>
</body>
</html>

where we need create folder templates and save the above html file as weather.html

and run the python code
then go to http://localhost:8888 we can see like



 The complete code Click Here


No comments:

Post a Comment

Blogger Widgets