GithubHelp home page GithubHelp logo

dvdme / forecastiopy Goto Github PK

View Code? Open in Web Editor NEW
26.0 3.0 38.0 253 KB

A Python wrapper for the forecast.io API.

License: Eclipse Public License 1.0

Python 100.00%
weather-data python python-wrapper darksky forecastio

forecastiopy's Introduction

Last update

The ForecastIO / DarkSky API is no longer available.

This repository has not been updated for a long time but since it is from the times I was starting my career and more people used this, it will reamin archived here.

Branch Travis CI
master Build Status
dev Build Status

ForcastIO Python

A Python wrapper for the darksky.net API (previously forecast.io). This started as port of my other wrapper ForecastIO-Lib-Java but as the languages are so different, this one took its own way. Anyway it is largely inspired by my previous Java wrapper. The API is fully implemented except for something I missed. Further development and improvements will continue.

Tested with the following Python version:

  • 2.7
  • 3.5
  • 3.6
  • 3.7-dev

What's new with 0.3

  • Logging support.

What's new with 0.21

  • Changed api url from old api.forecast.io to the new api.darksky.net

  • Some docstrings typos fixed

What's new with 0.2

  • Indexes of auto created properties now start in 0, 0 being the current day Issue #s

  • If the API key is invalid, an ValueError is raised Issue #3

  • Better Python 3 support

  • Other improvements

Quick Start:

Install the package:

pip install forecastiopy

Get the coordinates of your location, let's say Lisbon:

>>> Lisbon = [38.7252993, -9.1500364]

Get the current temperature and precipitation probability:

>>> from forecastiopy import *
>>> fio = ForecastIO.ForecastIO(YOUR_APY_KEY, latitude=Lisbon[0], longitude=Lisbon[1])
>>> current = FIOCurrently.FIOCurrently(fio)
>>> print 'Temperature:', current.temperature
Temperature: 11.07
>>> print 'Precipitation Probability:', current.precipProbability
Precipitation Probability: 0.29

What is does:

  • It can read Data Points and Data blocks from the darksky.net API.
    • This means it can read Currently, Minutely, Hourly, Daily, Flags and Alerts data.
  • It reads all available fields.
  • It reads all the available flags.
  • It reads all the available alerts.
  • It reads all the available errors.

What it does not:

  • It does not implements the callback request option.

To Do:

  • I'm not sure at this point in time but I'm sure something will appear.
  • I need to improve the docstrings

How it works:

The forecastiopy package has 9 classes. The main class is ForecastIO: It handles the connection, build the url and the gets the initial data from the API. The classes FIOCurrently, FIOMinutely, FIOHourly, FIODaily, FIOFlags and FIOAlerts contain the currently, minutely, hourly, daily, flags and alerts reports. Data can be accessed by the returned dictionary or directly by attributes made with reflection magic. See "Usage Examples" below.

Please refer to the API docs https://darksky.net/dev/ for better understanding of the data and for the API key. - You'll need a key to get it to work.

Dependencies:

Usage Examples

This instantiates the ForecastIO class

from forecastiopy import *

apikey = YOUR_APY_KEY

Lisbon = [38.7252993, -9.1500364]

fio = ForecastIO.ForecastIO(apikey,
                            units=ForecastIO.ForecastIO.UNITS_SI,
                            lang=ForecastIO.ForecastIO.LANG_ENGLISH,
                            latitude=Lisbon[0], longitude=Lisbon[1])
                            
print 'Latitude', fio.latitude, 'Longitude', fio.longitude
print 'Timezone', fio.timezone, 'Offset', fio.offset
print fio.get_url() # You might want to see the request url
print

Get Currently weather data for the requested location

if fio.has_currently() is True:
	currently = FIOCurrently.FIOCurrently(fio)
	print 'Currently'
	for item in currently.get().keys():
		print item + ' : ' + unicode(currently.get()[item])
	print
	# Or access attributes directly
	print currently.temperature
	print currently.humidity
	print
else:
	print 'No Currently data'

Get Minutely weather data for the requested location

if fio.has_minutely() is True:
	minutely = FIOMinutely.FIOMinutely(fio)
	print 'Minutely'
	print 'Summary:', minutely.summary
	print 'Icon:', minutely.icon
	print
	for minute in range(0, minutely.minutes()):
		print 'Minute', minute+1
		for item in minutely.get_minute(minute).keys():
			print item + ' : ' + unicode(minutely.get_minute(minute)[item])
		print
		# Or access attributes directly for a given minute. 
		# minutely.minute_3_time would also work
		print minutely.minute_1_time
		print
	print
else:
	print 'No Minutely data'

Get Hourly weather data for the requested location

if fio.has_hourly() is True:
	hourly = FIOHourly.FIOHourly(fio)
	print 'Hourly'
	print 'Summary:', hourly.summary
	print 'Icon:', hourly.icon
	print
	for hour in range(0, hourly.hours()):
		print 'Hour', hour+1
		for item in hourly.get_hour(hour).keys():
			print item + ' : ' + unicode(hourly.get_hour(hour)[item])
		print
		# Or access attributes directly for a given minute. 
		# hourly.hour_5_time would also work
		print hourly.hour_3_time
		print
	print
else:
	print 'No Hourly data'

Get Daily weather data for the requested location

if fio.has_daily() is True:
	daily = FIODaily.FIODaily(fio)
	print 'Daily'
	print 'Summary:', daily.summary
	print 'Icon:', daily.icon
	print
	for day in range(0, daily.days()):
		print 'Day', day+1
		for item in daily.get_day(day).keys():
			print item + ' : ' + unicode(daily.get_day(day)[item])
		print
		# Or access attributes directly for a given minute. 
		# daily.day_7_time would also work
		print daily.day_5_time
		print
	print
else:
	print 'No Daily data'

Get Flags weather data for the requested location

if fio.has_flags() is True:
	from pprint import pprint
	flags = FIOFlags.FIOFlags(fio)
	pprint(vars(flags))
	# Get units directly
	print flags.units
else:
	print 'No Flags data'

Get Alerts weather data for the requested location It should work just like Flags and the other ones, but at the time I am writting this I could not find a location with alerts to test on.

A note on time The API returns time in unix time. Although this is a good computer format, it is not particulary human-readable So, to get a more human-sane format, you can do soething like this:

import datetime

time = datetime.datetime.fromtimestamp(int(currently.time).strftime('%Y-%m-%d %H:%M:%S')
print 'unix time:', currently.time
print 'time:', time

Output should be like:

unix time: 1448234556
time: 2015-11-22 23:22:36

Issues

To report issues please do it in Github or send me an email.

Documentation

Thanks to pylint complaning, I did wrote docstring for everything!

Why I did this?

For fun. I like weather and weather data. And I like Python.

License

The code is available under the terms of the Eclipse Public License.

Contributors

  • Thanks to everyone that contribuited to make this software better.

Acknowledgements

Python Powered

Powered by Dark Sky

Jet Brains IntelliJ IDEA

Thanks to JetBrains for providing an open source license for.

forecastiopy's People

Contributors

dvdme avatar ellisvalentiner avatar pvthaggard avatar sclegg avatar zpriddy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

forecastiopy's Issues

Invalid API keys should be an exception

>>> fio = ForecastIO.ForecastIO("fds", latitude=83.6906, longitude=-39.4176)
The API Key doesn't seam to be valid.
>>> fio
<forecastiopy.ForecastIO.ForecastIO object at 0x7f573b300940>
>>> FIODaily.FIODaily(fio)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/kousu/.local/lib/python3.4/site-packages/forecastiopy-0.1-py3.4.egg/forecastiopy/FIODaily.py", line 20, in __init__
    if forecast_io.has_daily():
  File "/home/kousu/.local/lib/python3.4/site-packages/forecastiopy-0.1-py3.4.egg/forecastiopy/ForecastIO.py", line 204, in has_daily
    return 'daily' in self.forecast
AttributeError: 'ForecastIO' object has no attribute 'forecast'

The real mistake here is that the API key is wrong, but the exception that actually crashes is obscure and makes it seem like maybe there's a library version mismatch or something else frustratingly impossible to fix. I wrote a largish script, ported it to a new host, and accidentally misimported my API key, so I didn't notice the first message and was focusing on the second exception.

Would you make that initial line into an exception instead of just a print?

No attribute 'forecast' inside ForecastIO

Traceback (most recent call last):
  File "/home/olaf/.local/lib/python2.7/site-packages/flask/app.py", line 2000, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/olaf/.local/lib/python2.7/site-packages/flask/app.py", line 1991, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/home/olaf/.local/lib/python2.7/site-packages/flask/app.py", line 1567, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/home/olaf/.local/lib/python2.7/site-packages/flask/app.py", line 1988, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/olaf/.local/lib/python2.7/site-packages/flask/app.py", line 1641, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/olaf/.local/lib/python2.7/site-packages/flask/app.py", line 1544, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/olaf/.local/lib/python2.7/site-packages/flask/app.py", line 1639, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/olaf/.local/lib/python2.7/site-packages/flask/app.py", line 1625, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/olaf/Hackathons/Brumhack5/BrumHack5/jasien.py", line 49, in checkStuff
    weatherResult = getWeather(message_body_split[1])
  File "/home/olaf/Hackathons/Brumhack5/BrumHack5/jasien.py", line 26, in getWeather
    current = FIOCurrently.FIOCurrently(fio)
  File "/usr/local/lib/python2.7/dist-packages/forecastiopy/FIOCurrently.py", line 25, in __init__
    if forecast_io.has_currently():
  File "/usr/local/lib/python2.7/dist-packages/forecastiopy/ForecastIO.py", line 185, in has_currently
    return 'currently' in self.forecast
AttributeError: 'ForecastIO' object has no attribute 'forecast'

FIODaily off-by-one

In FIODaily, day_1_* is actually day 8 and everything else is shifted by 1:

# daily_cycle_bug.py
from forecastiopy import *
import time

YOUR_API_KEY = open("FORECASTIO_API_KEY.txt").read().strip()

location=[25.5, -83.566667]

fio = ForecastIO.ForecastIO(YOUR_API_KEY, latitude=location[0], longitude=location[1])
d = FIODaily.FIODaily(fio)

print(time.ctime(d.day_1_time))
print(time.ctime(d.day_2_time))
print(time.ctime(d.day_3_time))
print(time.ctime(d.day_4_time))
print(time.ctime(d.day_5_time))
print(time.ctime(d.day_6_time))
print(time.ctime(d.day_7_time))
print(time.ctime(d.day_8_time))

output:

$ python daily_cycle_bug.py 
Mon Sep  5 00:00:00 2016
Mon Aug 29 00:00:00 2016
Tue Aug 30 00:00:00 2016
Wed Aug 31 00:00:00 2016
Thu Sep  1 00:00:00 2016
Fri Sep  2 00:00:00 2016
Sat Sep  3 00:00:00 2016
Sun Sep  4 00:00:00 2016

time machine

Are you planning to implement a time-machine request of the API?
Thanks,
3.

Replace print calls with logging module

Thanks for this library and your efforts! ๐Ÿ‘

Looking into your source code, I would kindly suggest to replace all print calls with Python's logging module for the following reasons:

  • Easier to configure
  • Easier to test
  • Python's logging module allows to have different receivers for logging output (by stdout, mail, etc.)
  • Separates error messages from debug or information messages
  • Separates normal output for the user with logging output. Each serves different purposes.

Your code uses print a lot. For example, in file ForecastIO.py, there are a couple of prints. IMHO, I see the following problems with this approach:

  • Error messages should always go to stderr, never to stdout. If they go to stdout, they mix with "normal" messages for the user. It's hard or impossible to redirect error message into a file, for example.
  • If you really have to use print, redirect your output to stderr like this: print("error:", err, file=sys.stderr)

So better use logging.error instead of print as stated above. ๐Ÿ˜„

Exclude List ?

I'm trying to exclude daily,alerts etc and can't seem to get the syntax correct.
I've tried: excludeList = ['daily,alerts,flags'] and this excludeList = 'daily,alerts,flags'
and
fio = ForecastIO.ForecastIO(apikey,exclude=excludeList,
units=ForecastIO.ForecastIO.UNITS_US,
lang=ForecastIO.ForecastIO.LANG_ENGLISH,
latitude=Prado[0], longitude=Prado[1])

and this
fio = ForecastIO.ForecastIO(apikey,
units=ForecastIO.ForecastIO.UNITS_US,
lang=ForecastIO.ForecastIO.LANG_ENGLISH,
latitude=Prado[0], longitude=Prado[1],
exclude=excludeList )

The results are always
https://api.darksky.net/forecast/apikey/lattitude,longittude?units=us&lang=en

Appreciate your help

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.