Git Product home page Git Product logo

python-forecast.io's Introduction

Dark Sky Wrapper

image

This is a wrapper for the Dark Sky (formerly forecast.io) API. It allows you to get the weather for any location, now, in the past, or future.

The Basic Use section covers enough to get you going. I suggest also reading the source if you want to know more about how to use the wrapper or what its doing (it's very simple).

Installation

You should use pip to install python-forecastio.

  • To install pip install python-forecastio
  • To remove pip uninstall python-forecastio

Simple!

Requirements

Basic Use

Although you don't need to know anything about the Dark Sky API to use this module, their docs are available at https://darksky.net/dev/.

To use the wrapper:

import forecastio

api_key = "YOUR API KEY"
lat = -31.967819
lng = 115.87718

forecast = forecastio.load_forecast(api_key, lat, lng)
...

The load_forecast() method has a few optional parameters. Providing your API key, a latitude and longitude are the only required parameters.

Use the forecast.DataBlockType() eg. currently(), daily(), hourly(), minutely() methods to load the data you are after.

These methods return a DataBlock. Except currently() which returns a DataPoint.

byHour = forecast.hourly()
print byHour.summary
print byHour.icon

The .data attributes for each DataBlock is a list of DataPoint objects. This is where all the good data is :)

for hourlyData in byHour.data:
    print hourlyData.temperature

Advanced

function forecastio.load_forecast(key, latitude, longitude) ---------------------------------------------------

This makes an API request and returns a Forecast object (see below).

Parameters:
  • key - Your API key from https://darksky.net/dev/.
  • latitude - The latitude of the location for the forecast
  • longitude - The longitude of the location for the forecast
  • time - (optional) A datetime object for the forecast either in the past or future - see How Timezones Work below for the details on how timezones are handled in this library.
  • lang - (optional) A string of the desired language. See https://darksky.net/dev/docs/time-machine for supported languages.
  • units - (optional) A string of the preferred units of measurement, "auto" is the default. "us","ca","uk","si" are also available. See the API Docs (https://darksky.net/dev/docs/forecast) for exactly what each unit means.
  • lazy - (optional) Defaults to false. If true the function will request the json data as it is needed. Results in more requests, but maybe a faster response time.
  • callback - (optional) Pass a function to be used as a callback. If used, load_forecast() will use an asynchronous HTTP call and will not return the forecast object directly, instead it will be passed to the callback function. Make sure it can accept it.

function forecastio.manual(url)

This function allows manual creation of the URL for the Dark Sky API request. This method won't be required often but can be used to take advantage of new or beta features of the API which this wrapper does not support yet. Returns a Forecast object (see below).

Parameters:
  • url - The URL which the wrapper will attempt build a forecast from.
  • callback - (optional) Pass a function to be used as a callback. If used, an asynchronous HTTP call will be used and forecastio.manual will not return the forecast object directly, instead it will be passed to the callback function. Make sure it can accept it.

class forecastio.models.Forecast

The Forecast object, it contains both weather data and the HTTP response from Dark Sky

Attributes
  • response
  • http_headers
    • A dictionary of response headers. 'X-Forecast-API-Calls' might be of interest, it contains the number of API calls made by the given API key for today.
  • json
    • A dictionary containing the json data returned from the API call.
Methods
  • currently()
    • Returns a ForecastioDataPoint object
  • minutely()
    • Returns a ForecastioDataBlock object
  • hourly()
    • Returns a ForecastioDataBlock object
  • daily()
    • Returns a ForecastioDataBlock object
  • update()
    • Refreshes the forecast data by making a new request.

class forecastio.models.ForecastioDataBlock

Contains data about a forecast over time.

Attributes (descriptions taken from the darksky.net website)
  • summary
    • A human-readable text summary of this data block.
  • icon
    • A machine-readable text summary of this data block.
  • data
    • An array of ForecastioDataPoint objects (see below), ordered by time, which together describe the weather conditions at the requested location over time.

class forecastio.models.ForecastioDataPoint

Contains data about a forecast at a particular time.

Data points have many attributes, but not all of them are always available. Some commonly used ones are:

Attributes (descriptions taken from the darksky.net website)
  • summary
    • A human-readable text summary of this data block.
  • icon
    • A machine-readable text summary of this data block.
  • time
    • The time at which this data point occurs.
  • temperature
    • (not defined on daily data points): A numerical value representing the temperature at the given time.
  • precipProbability
    • A numerical value between 0 and 1 (inclusive) representing the probability of precipitation occurring at the given time.

For a full list of ForecastioDataPoint attributes and attribute descriptions, take a look at the Dark Sky data point documentation (https://darksky.net/dev/docs/response#data-point)


How Timezones Work

Requests with a naive datetime (no time zone specified) will correspond to the supplied time in the requesting location. If a timezone aware datetime object is supplied, the supplied time will be in the associated timezone.

Returned times eg the time parameter on the currently DataPoint are always in UTC time even if making a request with a timezone. If you want to manually convert to the locations local time, you can use the offset and timezone attributes of the forecast object.

Typically, would would want to do something like this:

# Amsterdam
lat  = 52.370235
lng  = 4.903549
current_time = datetime(2015, 2, 27, 6, 0, 0)
forecast = forecastio.load_forecast(api_key, lat, lng, time=current_time)

Be caerful, things can get confusing when doing something like the below. Given that I'm looking up the weather in Amsterdam (+2) while I'm in Perth, Australia (+8).

# Amsterdam
lat  = 52.370235
lng  = 4.903549

current_time = datetime.datetime.now()

forecast = forecastio.load_forecast(api_key, lat, lng, time=current_time)

The result is actually a request for the weather in the future in Amsterdam (by 6 hours). In addition, since all returned times are in UTC, it will report a time two hours behind the local time in Amsterdam.

If you're doing lots of queries in the past/future in different locations, the best approach is to consistently use UTC time. Keep in mind datetime.datetime.utcnow() is still a naive datetime. To use proper timezone aware datetime objects you will need to use a library like pytz

python-forecast.io's People

Contributors

austinlyons avatar bgilb avatar bowilliams avatar bzillins avatar chennin avatar dveeden avatar fabaff avatar fortinj1354 avatar laprice avatar pavelmachek avatar richardcornish avatar sawasy avatar theckman avatar zeevg 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  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  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  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  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  avatar  avatar  avatar

python-forecast.io's Issues

After installing python-forecastio, still cannnot import forecastio.

I have install the forecastio, and used the command as follows.

$ pip install python-forecastio

and then I ran the sample here.
https://gist.github.com/tjmcgi/c781881856b30cacef36
$ python forecastio.py

But...it seemed can not work successfully.

Traceback (most recent call last):
File "forecastio.py", line 1, in
import forecastio
File "/home/huang/weather_test/forecastio.py", line 62, in
forecast = forecastio.load_forecast('(API_Key)',35.689487,139.691706)
AttributeError: 'module' object has no attribute 'load_forecast'

So I try to merely import the package in python.
But it seemed I even cannot import the forecastio package.

$ import forecastio

Traceback (most recent call last):
File "", line 1, in
File "forecastio.py", line 62, in
forecast = forecastio.load_forecast('(API_Key)',35.689487,139.691706)
AttributeError: 'module' object has no attribute 'load_forecast'

I just follow all the steps and have checked if I have installed the package.
Does anyone have any suggestion to solve this kind of problem ?
Thank you very much.

502 errors

thank you very much for your wrapper.
i've built production tools that use it multiple times daily.

ive noticed that im receiving multiple 502 errors for multiple lat-longs, and various times of the day.

502 Server Error: Bad Gateway for url: https://api.darksky.net/forecast/{token}/37.2972061,-121.9574981,2018-01-20T20:35:13+00:00?units=auto

have you seen these errors before?
do you know what could be causing them?

thanks,
dani

Add alert objects

the forecast.io api will provide an alert object if there is a weather watch or warning in the area. It would be useful to be able to access it.

Fix simple typo: caerful -> careful

Issue Type

[x] Bug (Typo)

Steps to Replicate

  1. Examine README.rst.
  2. Search for caerful.

Expected Behaviour

  1. Should read careful.

Semi-automated issue generated by
https://github.com/timgates42/meticulous/blob/master/docs/NOTE.md

To avoid wasting CI processing resources a branch with the fix has been
prepared but a pull request has not yet been created. A pull request fixing
the issue can be prepared from the link below, feel free to create it or
request @timgates42 create the PR. Alternatively if the fix is undesired please
close the issue with a small comment about the reasoning.

https://github.com/timgates42/python-forecast.io/pull/new/bugfix_typo_careful

Thanks.

Flags Object

What is the correct way to create a Flag Object so that I can then proceed to gather the following data:

nearest-station required
The distance to the nearest weather station that contributed data to this response. Note, however, that many other stations may have also been used; this value is primarily for debugging purposes. This property's value is in miles (if US units are selected) or kilometers (if SI units are selected).
sources required
This property contains an array of IDs for each data source utilized in servicing this request.
units required
Indicates the units which were used for the data in this request.

I have been successful at creating DataPoint Objects, DataBlock Objects, and Alerts Arrays; but so far I have been unable to create a flag object. I cant find any documentation as to how to properly create one, I have been trying this:

forecast = forecastio.load_forecast(api_key, lat, lng)
ws = forecast.flags()

but it yields:

AttributeError: 'Forecast' object has no attribute 'flags'

I need it to find out from what weather station is being used.

Thanks!!!

Buggy temperature responses?

I tried to use this library and it was a success, it worked but the problem is that when I queried for the temperature for New York, it shows somewhat like 53°C which is not true but its 53°F. Other places have right responses like Cebu, Philippines and shows 29°C or something which is true. It might be just me but thanks in advance for clarifying on this one

Geocoding Forecasts

I would be good if an address could be used for the forecast location instead of a lat and long.

error 403 forbidden

I've been using this module for a long time and I'd never get this kind of error:

#HTTPERROR: 403 Cliente Error: Forbidden for url: https://api.darksky.net/forecast/my_api_key/39.929,116.417,2018-05-03-03T00:00:00?units=auto&lang=en

I can see that I can't download data for some reason, but the same code was working yesterday and I didn't reach my call limit.

I'm using the function forecastio.load_forecast

Any clue?

Thank you.

Can we no longer get an API key?

I am trying to run a basic Python example from your GitHub repo for which I need an API key. Your website says "We are no longer accepting new signups." Does this mean it is no longer possible to obtain an API key?

Time error

Hello

When I make a load forecast like this

api_key = "xxxx"
lat = xxxx
lng = xxxx
time = "2015-01-06 12:00:00"
forecast = forecastio.load_forecast(api_key, lat, lng, time)

python returns the following error

'str' object has no attribute 'timetuple'

Could you help me?

No JSON object could be decoded

Hello. When I run your example script, I get this error :

Traceback (most recent call last):
  File "main.py", line 16, in <module>
    forecast = forecastio.load_forecast(api_key, lat, lng)
  File "/usr/local/lib/python2.7/dist-packages/forecastio/api.py", line 41, in load_forecast
    return manual(baseURL, callback=callback)
  File "/usr/local/lib/python2.7/dist-packages/forecastio/api.py", line 51, in manual
    return get_forecast(requestURL)
  File "/usr/local/lib/python2.7/dist-packages/forecastio/api.py", line 61, in get_forecast
    json = forecastio_reponse.json()
  File "/usr/lib/python2.7/dist-packages/requests/models.py", line 741, in json
    return json.loads(self.text, **kwargs)
  File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/decoder.py", line 384, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

Of course, I use the my API Key

Impliment a better way to handle API options

Currently some of the API options (https://developer.forecast.io/docs/v2#options) can be accessed by optional function parameters to load_forecast().

The forecast units is an example of an API option which is supported. However there is a need to properly support additional options see #25 #19. Currently these use cases are being supported by manually constructing a url and using forecastio.manual()

I am hesitant to clutter up load_forecast() with many optional parameters especially since it is likely more are made available by forecast.io in the future.

A possible solution is to pass any optional parameters to load_forecast() as a dictionary where it would work something like this...

options = {
    'units': 'si',
    'lang': 'es',
    'solar': True
}

forecastio.load_forecast(api_key, lat, lng, options)

The dictionary key/value would be transformed to the GET parameter name/value - the forecast.io API options are really just GET parameters.

This change would break backwards compatibility and so should be implemented along with the other changes planned for version 2.0 - see Milestone v2.

not downloading on raspberry pi (raspbian)

entered the command sudo pip install python-forecastio in to terminal and it come out with this: (yes i do have PIP)


pi@raspberrypi ~ $ sudo pip install python-forecastio
Downloading/unpacking python-forecastio
Running setup.py egg_info for package python-forecastio

Downloading/unpacking requests>=1.6 (from python-forecastio)
Running setup.py egg_info for package requests

Downloading/unpacking responses (from python-forecastio)
Running setup.py egg_info for package responses
No handlers could be found for logger "main"

Downloading/unpacking cookies (from responses->python-forecastio)
Running setup.py egg_info for package cookies

Requirement already satisfied (use --upgrade to upgrade): six in /usr/local/lib/python2.7/dist-packages (from responses->python-forecastio)
Downloading/unpacking mock (from responses->python-forecastio)
Running setup.py egg_info for package mock
mock requires setuptools>=17.1. Aborting installation
Complete output from command python setup.py egg_info:
mock requires setuptools>=17.1. Aborting installation


Command python setup.py egg_info failed with error code 1 in /home/pi/build/mock
Storing complete log in /root/.pip/pip.log

Requests dependency

The installation through pip install python-forecastio fails if requests module is not installed.

Either this gets fixed in the setup.py, or this dependency may be added in the Requirements section of README.md.

Handling non-ASCII characters in README.rst on Python 3

I'm a paying customer at forecast.io and I'm running into a strange issue with python-forecast.io, but am struggling to re-produce it under my own conditions.

When I build docs for my project on readthedocs.org using a Python 3 runtime, I get the following error:

Downloading/unpacking python-forecastio==1.3.1 (from -r requirements.txt (line 11))
  Downloading python-forecastio-1.3.1.tar.gz
  Running setup.py (path:/var/build/user_builds/codefurther/envs/master/build/python-forecastio/setup.py) egg_info for package python-forecastio
    Traceback (most recent call last):
      File "<string>", line 17, in <module>
      File "/var/build/user_builds/codefurther/envs/master/build/python-forecastio/setup.py", line 28, in <module>
        long_description=open('README.rst').read(),
      File "/home/docs/checkouts/readthedocs.org/user_builds/codefurther/envs/master/lib/python3.4/encodings/ascii.py", line 26, in decode
        return codecs.ascii_decode(input, self.errors)[0]
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 425: ordinal not in range(128)
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):

  File "<string>", line 17, in <module>

  File "/var/build/user_builds/codefurther/envs/master/build/python-forecastio/setup.py", line 28, in <module>

    long_description=open('README.rst').read(),

  File "/home/docs/checkouts/readthedocs.org/user_builds/codefurther/envs/master/lib/python3.4/encodings/ascii.py", line 26, in decode

    return codecs.ascii_decode(input, self.errors)[0]

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 425: ordinal not in range(128)

However, if I use Python 2, I do not see the error. A colleague who is helping me to test my package on Mac also gets the same error on Python 3.4.2. However, I can't reproduce the problem on either Windows under 3.4.1 or Ubuntu on 3.4.0.

I've looked at the README.rst file and sure enough the apostrophe in the following text

...what its doing (it’s very simple).

appears to be somewhat exotic as my test code shows...

w
h
a
t

i
t
s

d
o
i
n
g

(
i
t
Non-ASCII char found! at pos 425 ( 0x1a9 ) character is â
Non-ASCII char found! at pos 426 ( 0x1aa ) character is €
Non-ASCII char found! at pos 427 ( 0x1ab ) character is ™
s 

I've forked python-forecastio and made a change to setup.py so that it handles and decodes non-ascii characters. See 52b7f4c. I tried to use the read() function that was present, but not actually used.

With this change made, and by using my forked repository on GitHub in my own project's setup.py, my docs on readthedocs.org now build correctly.

Can you please advise if you think there is an issue, and if so I guess you could either remove the non-ascii chars in README.rst, or I'd happily offer a pull request.

Great module

Fix time representation and timezone issues

The way times (and dates) are handled is inconsistent and needs an overhaul.

Times are represented using a mix Python datetime objects and unix timestamps. This needs to be standardised to Python objects. Also, when using times, it is not clear what time zone the API expects. Is it local time or the time at the forecast location? This all needs to be cleaned up and documented.

One option (this is the approach that Forecast.io has taken) is to always use UTC time.

This is probably my prefered approach as it will standardise the representation of time within the wrapper and also between the wrapper and the HTTP API.

1.3.5

Can you please publish a new release? Including #41.

Thanks in advance.

minutely()

While playing around with python-forecast.io. I have trouble to get the minutely data. With hourly() it works like a charm

>>> import forecastio
>>> forecast = forecastio.load_forecast('3xxxx', 46.9167, 7.4667)
>>> hour = forecast.hourly()
>>> print(hour.summary)
Light rain starting tomorrow afternoon.

but minutely() seems to get no data.

>>> minute = forecast.minutely()
>>> print(minute.summary)
None
>>> print(minute.icon)
None

Question: Rational behind second API call?

I was wondering what was the rationale behind this second API call? When the key is not in response json wont that mean data is not available? Thanks for clarifying.

   def _forcastio_data(self, key):
        keys = ['minutely', 'currently', 'hourly', 'daily']
        try:
            if key not in self.json:
                keys.remove(key)
                url = "%s&exclude=%s%s" % (self.response.url.split('&')[0],
                      ','.join(keys), ',alerts,flags')

                response = requests.get(url).json()
                self.json[key] = response[key]

            if key == 'currently':
                return ForecastioDataPoint(self.json[key])
            else:
                return ForecastioDataBlock(self.json[key])

alerts not updated

when a call to Forecast update() is made, the alerts don't seem to get updated

in init you have

        self._alerts = []
        for alertJSON in self.json.get('alerts', []):
            self._alerts.append(Alert(alertJSON))

but in update nothing happens to _alerts

is that on purpose?

Option to return 'None' instead of KeyError

In reference to PR #40 , I think it would be useful to add an option to return 'None' instead of raising a KeyError when dealing with weather attributes that don't have data associated with them.

I'm using Dark Sky's API for historical data collection, so raising a KeyError doesn't allow me to generate a full dataset without writing a try-except to ignore the PropertyUnavailable exception. I know that there's a focus on keeping load_forecast() pretty simple and not bogging it down with tons of parameters, but this could be a nice one to add for those using the package for historical data purposes.

I'd be happy to write it and submit a PR if there's interest or perceived use-value.

A way to reload forecast in lazy mode with out the double call overhead

I am currently using load_forecast() with lazy loading because I'm interested in only data from currently and want to minimize data transferred. When I load_forecast() it takes one API call. When I call get_currently() it takes another. If I wanted to get fresh data I would need to call load_forecast() again. This again takes another API call.

It would be nice if load_forecast() didn't take up an API call on subsequent requests. Or, a way to clear the data so the next call to get_currently() lazily fetched new data.

Support language

Under the Docs for v2 is an lang= Option.
It would be nice to see this implemented as something like this:

foo = forecastio.load_forecast(key, latitude, longitude, lang="en")

This was added to the API on 29 May 2014:
https://developer.forecast.io/docs/v2#options

Currently this is not working. Are there any quick workarounds?

Problems installing on mac, python 3.4.1

Maybe you can have a look, not sure if it is related to your package, but other modules did install.

Install packages failed: Error occurred when installing package python-forecastio. 

The following command was executed:

packaging_tool.py install --build-dir /private/var/folders/gj/84mj91y514z79t19xfc8t8sr0000gn/T/pycharm-packaging5452297355347498062.tmp --user python-forecastio

The error output of the command:

Traceback (most recent call last):
  File "/Applications/PyCharm.app/helpers/packaging_tool.py", line 56, in do_install
    import pip
  File "/usr/local/Cellar/python3/3.4.1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/pip/__init__.py", line 10, in <module>
    from pip.util import get_installed_distributions, get_prog
  File "/usr/local/Cellar/python3/3.4.1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/pip/util.py", line 18, in <module>
    from pip._vendor.distlib import version
  File "/usr/local/Cellar/python3/3.4.1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/pip/_vendor/distlib/version.py", line 14, in <module>
    from .compat import string_types
  File "/usr/local/Cellar/python3/3.4.1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/pip/_vendor/distlib/compat.py", line 66, in <module>
    from urllib.request import (urlopen, urlretrieve, Request, url2pathname,
ImportError: cannot import name 'HTTPSHandler'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Applications/PyCharm.app/helpers/packaging_tool.py", line 125, in main
    retcode = do_install(pkgs)
  File "/Applications/PyCharm.app/helpers/packaging_tool.py", line 58, in do_install
    error_no_pip()
  File "/Applications/PyCharm.app/helpers/packaging_tool.py", line 36, in error_no_pip
    tb = sys.exc_traceback
AttributeError: 'module' object has no attribute 'exc_traceback'

currently option is broken

Following errors occurs when trying to use currently method

currently = forecast.currently()
currently.data
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/python_forecastio-1.3.5-py3.4.egg/forecastio/models.py", line 103, in getattr
KeyError: 'data'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "", line 1, in
File "/usr/local/lib/python3.4/dist-packages/python_forecastio-1.3.5-py3.4.egg/forecastio/models.py", line 107, in getattr
forecastio.utils.PropertyUnavailable: Property 'data' is not valid or is not available for this forecast

Question on extracting weather data

I am still familiarising myself with the data structure in darksky. Could I get some help with it?

When I ran the example script to get the daily data, it returns with:
<ForecastioDataPoint instance: Mostly Cloudy at 2018-01-25 16:18:40>

I checked the data type and it appears to be a list. I then tried to use index, but there was only one data listed in by_day.data[0]. There is no data in by_day.data[1] when I queried. How can I obtain the individual data, like 'Mostly Cloudy' excluding the other bits as the whole chunk of info seems to come together when queried?

Forecast __unicode__ attribute error

I'm running into an issue, whether I use forecastio with 2.7 or 3.4, where I'm getting the following error:

AttributeError: "'Forecast' object has no attribute 'unicode'"

Not sure what I'm doing wrong or if this is a legit bug. Thanks in advance!

Json error in python 3.

When using python 3 with this library, I get this error.
Traceback (most recent call last):
File "C:\Users\Derek Riemer\Google Drive\python\weather\weather.py", line 59, in
args.func(args)
File "C:\Users\Derek Riemer\Google Drive\python\weather\weather.py", line 12, in getWeather
forecast.start(location.get('lat'), location.get('lng'), args.forecast)
File "C:\Users\Derek Riemer\Google Drive\python\weather\forecast.py", line 103, in start
forecast = forecastio.load_forecast(api_key, lat, lng)
File "C:\Python34\lib\site-packages\forecastio\api.py", line 41, in load_forecast
return manual(baseURL, callback=callback)
File "C:\Python34\lib\site-packages\forecastio\api.py", line 51, in manual
return get_forecast(requestURL)
File "C:\Python34\lib\site-packages\forecastio\api.py", line 61, in get_forecast
json = forecastio_reponse.json()
File "C:\Python34\lib\site-packages\requests\models.py", line 819, in json
return json.loads(self.text, **kwargs)
File "C:\Python34\lib\json__init__.py", line 318, in loads
return _default_decoder.decode(s)
File "C:\Python34\lib\json\decoder.py", line 343, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python34\lib\json\decoder.py", line 361, in raw_decode
raise ValueError(errmsg("Expecting value", s, err.value)) from None
ValueError: Expecting value: line 1 column 1 (char 0)

I get the same error in django where I am playing around with weather data on a website. I dug into this a bit and I can't quite pinpoint any reason why this shouldn't work. Some people have had this error before on stack overflow, but I didn't really find a cure for the issue there, besides the possibility of malformed json.
it works fine with python2, but I didn't see anything about which versions of python it should work with.

alerts not functioning correctly

alerts doesn't appear to function correctly
.>>> forecast = forecastio.load_forecast(api_key, lat, long)
.>>> alerts = forecast.alerts()
.>>> alerts
[]

example uses deprecated functions

hi,

The example code still uses the deprecated functions so it isn't a very good example anymore (not even a working one at that!). If I get time this weekend I will fix it if it hasn't been done yet.

Cheers,

-S

Can't handle for forecastio.utils.PropertyUnavailable keyError

I've got a script built to report daily data forecasts, but sometimes I get the forecastio.utils.PropertyUnavailable error. I understand that this means there is no data for the particular forecast item I'm looking for. What I'm asking is how do I handle for these errors? This error is causing my script not to finish retrieving the forecast because of this error.

Traceback (most recent call last):
  File "/home/user/.local/lib/python3.6/site-packages/forecastio/models.py", line 103, in __getattr__
    return self.d[name]
KeyError: 'precipType'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "DarkSky.py", line 100, in <module>
    main()
  File "DarkSky.py", line 97, in main
    getDaily(forecast_data)
  File "DarkSky.py", line 70, in getDaily
    'Precip_Type' : i.precipType,
  File "/home/user/.local/lib/python3.6/site-packages/forecastio/models.py", line 107, in __getattr__
    " or is not available for this forecast".format(name)
forecastio.utils.PropertyUnavailable: Property 'precipType' is not valid or is not available for this forecast

I'd be fine with being able to say something like:
'Precipitation Type: none or no precipitation type data exists for this forecast'

The problem is I can't figure out how to handle for this error.

I've tried


exception KeyError:
    print('No data exists for this forecast variable')

and

exception forecastio.utils.PropertyUnavailable:
    print('No data exists for this forecast variable')

But neither of these work. I noticed in the traceback that this ultimately results from a KeyError exception, but using this as an Exception raise doesn't work.

Can anyone help with how to handle for these errors? Thanks

importing forecastio fails

,>>> current_time = datetime.datetime.now()
,>>> current_time
,datetime.datetime(2016, 10, 25, 23, 35, 11, 279322)
,>>> self.forecast = forecastio.load_forecast(api_key, lat, long, time=current_time)
,Traceback (most recent call last):
,File "", line 1, in
,File "/usr/local/lib/python3.4/dist-packages/python_forecastio-1.3.5-py3.4.egg/forecastio/api.py", line ,41, in load_forecast
,File "/usr/local/lib/python3.4/dist-packages/python_forecastio-1.3.5-py3.4.egg/forecastio/api.py", line ,51, in manual
,File "/usr/local/lib/python3.4/dist-packages/python_forecastio-1.3.5-py3.4.egg/forecastio/api.py", line ,60, in get_forecast
,File "/usr/lib/python3/dist-packages/requests/models.py", line 825, in raise_for_status
,raise HTTPError(http_error_msg, response=self)
,requests.exceptions.HTTPError: 404 Client Error: Not Found

Pip install not working

Hey,

This is super useful and I love it. Had to install manually as pip install couldn't find a matching package. When I searched for it, it recommended python-forcastio (<--that's not a typo), but said there was no matching version for pypi to install.

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.