Package: metno-locationforecast
MET Norway Location ForecastA Python interface for the MET NorwayLocationforecast/2.0service. This is a free weather data service provided by theNorwegian
Meteorological Institute.ContentsFeaturesInstallationUsageBasicsAccessing DataCustom URLsConfigurationMore ExamplesNotes on LicensingDependenciesUseful LinksFeaturesGet weather data for anywhere in the worldAutomatically take care of caching dataHelpful classes for managing forecast dataConvert between units of measurementInstallationInstalling with pip:pipinstallmetno-locationforecastIt's recommended to installmetno-locationforecastinto a virtual
environment for your application.UsageBasicsBefore using this package you should be aware of theterms of
servicefor using the MET Weather API.Themetno-locationforecastpackage will not make requests unless current
data has expired and will send requests with the appropriateIf-Modified-Sinceheader where possible. Identification can be provided by
passing aUser-Agentstring to the forecast class, see more on this below.After installingmetno-locationforecastthe following commands can be run
in a python console. Start by importing thePlaceandForecastclasses, these are the main classes you will need to interact with.>>>frommetno_locationforecastimportPlace,ForecastNote:Use an underscore in the name when importing.Create aPlaceinstance. The first argument is your name for the place,
next are the geographic coordinates. Geographic coordinates are given by
latitude, longitude (in degrees) and altitude (in metres).>>>new_york=Place("New York",40.7,-74.0,10)The altitude parameter is optional but recommended. Note that latitude and
longitude are rounded to four decimal places and altitude is rounded to the
nearest integer, this is required by the MET API.GeoNamesis a helpful website for finding the
geographic coordinates of a place.Next create aForecastinstance for the place. Here you need to supply aUser-Agentstring, typically this will include the name and version of
your application as well as contact information (email address or website) more
details on what is expectedhere. Do
NOT use the string supplied here as this does not apply to your site.>>>ny_forecast=Forecast(new_york,"metno-locationforecast/1.0 https://github.com/Rory-Sullivan/metno-locationforecast")There are also three optional arguments that you can supply. First is theforecast_typeparameter, options are"compact"(a limited set of
variables suitable for most purposes) or"complete"(an extensive set of
weather data). For more details on the differences check out the thispage."compact"is
the default.The second optional parameter issave_location, this is the folder where
data will be stored. The default is"./data/". Finally there is thebase_urlparameter, more on this in theCustom URLssection.These parameters can be configured for your entire app by using a configuration
file, more on this in theconfigurationsection.Next run the update method. This will make a request to the MET API for data and
will save the data to the save location. If data already exists for the
forecast, this will only request new data if the data has expired and will make
the request using the appropriateIf-Modified-Sinceheader. It returns a
string describing which process occurred, this will be one of'Data-Not-Expired','Data-Not-Modified'or'Data-Modified'.
Only in the case of'Data-Modified'has any change to the data occurred.>>>ny_forecast.update()'Data-Modified'>>>ny_forecast.update()'Data-Not-Expired'Finally we can print the forecast.>>>print(ny_forecast)Forecast for New York:Forecast between 2020-07-21 14:00:00 and 2020-07-21 15:00:00:air_pressure_at_sea_level: 1016.7hPaair_temperature: 28.7celsiuscloud_area_fraction: 1.6%...Accessing DataPrinting forecasts to the terminal is great but most likely you want to use the
forecast data in your own application. When the update method is run it parses
the returned data which can then be accessed through attributes of the forecast
instance.The most notable of these is thedataattribute.>>>type(ny_forecast.data)<class 'metno_locationforecast.data_containers.Data'>This is a specialDataclass which stores the weather data information.
You can list its attributes like so;>>>vars(ny_forecast.data).keys()dict_keys(['last_modified', 'expires', 'updated_at', 'units', 'intervals'])last_modified,expiresandupdated_ataredatetime.datetimeobjects for when the data was last modified, when it is
expected to expire and when the forecast was updated, respectively.unitscontains a dictionary mapping variable names to the units in which
they are provided by the API.intervalsis where we find the actual weather data. It is a list of
intervals. Note that the MET API usually supplies multiple intervals for each
time point in the data set, the forecast parser takes theshortestsupplied
interval for each time point.>>>type(ny_forecast.data.intervals)<class 'list'>>>>type(ny_forecast.data.intervals[0])<class 'metno_locationforecast.data_containers.Interval'>>>>print(ny_forecast.data.intervals[0])Forecast between 2020-07-21 14:00:00 and 2020-07-21 15:00:00:air_pressure_at_sea_level: 1016.7hPaair_temperature: 28.7celsiuscloud_area_fraction: 1.6%relative_humidity: 56.0%wind_from_direction: 349.7degreeswind_speed: 1.4m/sprecipitation_amount: 0.0mmEach interval is anIntervalinstance. This interval class has avariablesattribute which is a dictionary mapping variable names toVariableinstances.>>>first_interval=ny_forecast.data.intervals[0]>>>first_interval.start_timedatetime.datetime(2020, 7, 21, 14, 0)>>>first_interval.end_timedatetime.datetime(2020, 7, 21, 15, 0)>>>first_interval.durationdatetime.timedelta(0, 3600)>>>first_interval.variables.keys()dict_keys(['air_pressure_at_sea_level', 'air_temperature', 'cloud_area_fraction', 'relative_humidity', 'wind_from_direction', 'wind_speed', 'precipitation_amount'])>>>>>>rain=first_interval.variables["precipitation_amount"]>>>print(rain)precipitation_amount: 0.0mm>>>rain.value0.0>>>rain.units'mm'For a full overview of theData,IntervalandVariableclasses
see thecode.Other attributes of theForecastclass that could be useful are;response: This is the fullrequests.Responseobject received from the
MET API (metno-locationforecast uses therequestslibrary).json_string: A string containing all data in json format. This is what is
saved.json: An object representation of the json_string.TheForecastclass also has additional methods that may be of use.save(): Save data to save location.load(): Load data from saved file.The code for theForecastclass can be foundhere.Custom URLsBy default the Forecast class will fetch data from
'https://api.met.no/weatherapi/locationforecast/2.0/' if you wish to use a
different domain you can pass abase_urlparameter to the constructor
function. Note that the type for the forecast will be appended to this url when
requests are made, if this is not suitable for your application you should pass
an empty string for the type.>>>ny_forecast=Forecast(new_york,"metno-locationforecast/1.0",forecast_type="",base_url="somewhere.com")>>>ny_forecast.url'somewhere.com'ConfigurationIf you wish to provide application wide configuration for your module this can
be done in either ametno-locationforecast.inifile or in asetup.cfgfile in the root directory of your application. Below is an example of the
configurations that you can put in there showing their default values.[metno-locationforecast]user_agent=Noneforecast_type=compactsave_location=./database_url=https://api.met.no/weatherapi/locationforecast/2.0/Note that regardless of the file, configurations need to be under a[metno-locationforecast]section and settings in ametno-locationforecast.inifile will take precedence.More ExamplesFor further usage examples see theexamplesfolder.To see what can be done with this library you could also checkoutDry
Rock. It is another project
maintained by myself that uses themetno-locationforecastlibrary. It was
in fact the original inspiration for me to create this library.Notes on LicensingWhile the code in this package is covered by an MIT license and is free to use
the weather data collected from the MET Weather API is covered by a separate
license and has it's ownterms of use.DependenciesRequestsUseful LinksPyPI page -https://pypi.org/project/metno-locationforecast/Github page -https://github.com/Rory-Sullivan/metno-locationforecastThe Norwegian Meteorological Institute -https://www.met.no/enMET Weather API -https://api.met.no/MET Weather API Terms of Service -https://api.met.no/doc/TermsOfServiceLocationforecast/2.0 documentation -https://api.met.no/weatherapi/locationforecast/2.0Full list of variables and their names -https://api.met.no/doc/locationforecast/datamodelYr Developer Portal -https://developer.yr.no/Yr Terms of Service (same as the MET API terms of service but perhaps more readable) -https://developer.yr.no/doc/TermsOfService/GeoNames -http://www.geonames.org/Requests library -https://requests.readthedocs.io/en/master/