datapackage-py
A library for working with Data Packages.
[Important Notice] We have released Frictionless Framework. This framework provides improved datapackage functionality extended to be a complete data solution. The change in not breaking for the existing software so no actions are required. Please read the Migration Guide from datapackage to Frictionless Framework.
Features
Package class for working with data packages
Resource class for working with data resources
Profile class for working with profiles
validate function for validating data package descriptors
infer function for inferring data package descriptors
Contents
Getting Started
Installation
The package use semantic versioning. It means that major versions could include breaking changes. It's highly recommended to specify datapackage version range in your setup/requirements file e.g. datapackage>=1.0,<2.0.
$ pip install datapackage
OSX 10.14+
If you receive an error about the cchardet package when installing datapackage on Mac OSX 10.14 (Mojave) or higher, follow these steps:
- Make sure you have the latest x-code by running the following in terminal:
xcode-select --install
- Then go to https://developer.apple.com/download/more/ and download the
command line tools. Note, this requires an Apple ID.
- Then, in terminal, run
open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg
You can read more about these steps in this post.
Documentation
Introduction
Let's start with a simple example:
from datapackage import Package
package = Package('datapackage.json')
package.get_resource('resource').read()
Working with Package
A class for working with data packages. It provides various capabilities like loading local or remote data package, inferring a data package descriptor, saving a data package descriptor and many more.
Consider we have some local csv files in a data directory. Let's create a data package based on this data using a Package class:
data/cities.csv
city,location
london,"51.50,-0.11"
paris,"48.85,2.30"
rome,"41.89,12.51"
data/population.csv
city,year,population
london,2017,8780000
paris,2017,2240000
rome,2017,2860000
First we create a blank data package:
package = Package()
Now we're ready to infer a data package descriptor based on data files we have. Because we have two csv files we use glob pattern **/*.csv:
package.infer('**/*.csv')
package.descriptor
#{ profile: 'tabular-data-package',
# resources:
# [ { path: 'data/cities.csv',
# profile: 'tabular-data-resource',
# encoding: 'utf-8',
# name: 'cities',
# format: 'csv',
# mediatype: 'text/csv',
# schema: [Object] },
# { path: 'data/population.csv',
# profile: 'tabular-data-resource',
# encoding: 'utf-8',
# name: 'population',
# format: 'csv',
# mediatype: 'text/csv',
# schema: [Object] } ] }
An infer method has found all our files and inspected it to extract useful metadata like profile, encoding, format, Table Schema etc. Let's tweak it a little bit:
package.descriptor['resources'][1]['schema']['fields'][1]['type'] = 'year'
package.commit()
package.valid # true
Because our resources are tabular we could read it as a tabular data:
package.get_resource('population').read(keyed=True)
#[ { city: 'london', year: 2017, population: 8780000 },
# { city: 'paris', year: 2017, population: 2240000 },
# { city: 'rome', year: 2017, population: 2860000 } ]
Let's save our descriptor on the disk as a zip-file:
package.save('datapackage.zip')
To continue the work with the data package we just load it again but this time using local datapackage.zip:
package = Package('datapackage.zip')
# Continue the work
It was onle basic introduction to the Package class. To learn more let's take a look on Package class API reference.
Working with Resource
A class for working with data resources. You can read or iterate tabular resources using the iter/read methods and all resource as bytes using row_iter/row_read methods.
Consider we have some local csv file. It could be inline data or remote link - all supported by Resource class (except local files for in-brower usage of course). But say it's data.csv for now:
city,location
london,"51.50,-0.11"
paris,"48.85,2.30"
rome,N/A
Let's create and read a resource. Because resource is tabular we could use resource.read method with a keyed option to get an array of keyed rows:
resource = Resource({path: 'data.csv'})
resource.tabular # true
resource.read(keyed=True)
# [
# {city: 'london', location: '51.50,-0.11'},
# {city: 'paris', location: '48.85,2.30'},
# {city: 'rome', location: 'N/A'},
# ]
resource.headers
# ['city', 'location']
# (reading has to be started first)
As we could see our locations are just a strings. But it should be geopoints. Also Rome's location is not available but it's also just a N/A string instead of Python None. First we have to infer resource metadata:
resource.infer()
resource.descriptor
#{ path: 'data.csv',
# profile: 'tabular-data-resource',
# encoding: 'utf-8',
# name: 'data',
# format: 'csv',
# mediatype: 'text/csv',
# schema: { fields: [ [Object], [Object] ], missingValues: [ '' ] } }
resource.read(keyed=True)
# Fails with a data validation error
Let's fix not available location. There is a missingValues property in Table Schema specification. As a first try we set missingValues to N/A in resource.descriptor.schema. Resource descriptor could be changed in-place but all changes should be commited by resource.commit():
resource.descriptor['schema']['missingValues'] = 'N/A'
resource.commit()
resource.valid # False
resource.errors
# [<ValidationError: "'N/A' is not of type 'array'">]
As a good citiziens we've decided to check out recource descriptor validity. And it's not valid! We should use an array for missingValues property. Also don't forget to have an empty string as a missing value:
resource.descriptor['schema']['missingValues'] = ['', 'N/A']
resource.commit()
resource.valid # true
All good. It looks like we're ready to read our data again:
resource.read(keyed=True)
# [
# {city: 'london', location: [51.50,-0.11]},
# {city: 'paris', location: [48.85,2.30]},
# {city: 'rome', location: null},
# ]
Now we see that:
- locations are arrays with numeric lattide and longitude
- Rome's location is a native JavaScript
null
And because there are no errors on data reading we could be sure that our data is valid againt our schema. Let's save our resource descriptor:
resource.save('dataresource.json')
Let's check newly-crated dataresource.json. It contains path to our data file, inferred metadata and our missingValues tweak:
{
"path": "data.csv",
"profile": "tabular-data-resource",
"encoding": "utf-8",
"name": "data",
"format": "csv",
"mediatype": "text/csv",
"schema": {
"fields": [
{
"name": "city",
"type": "string",
"format": "default"
},
{
"name": "location",
"type": "geopoint",
"format": "default"
}
],
"missingValues": [
"",
"N/A"
]
}
}
If we decide to improve it even more we could update the dataresource.json file and then open it again using local file name:
resource = Resource('dataresource.json')
# Continue the work
It was onle basic introduction to the Resource class. To learn more let's take a look on Resource class API reference.
Working with Group
A class representing a group of tabular resources. Groups can be used to read multiple resource as one or to export them, for example, to a database as one table. To define a group add the group: <name> field to corresponding resources. The group's metadata will be created from the "leading" resource's metadata (the first resource with the group name).
Consider we have a data package with two tables partitioned by a year and a shared schema stored separately:
cars-2017.csv
name,value
bmw,2017
tesla,2017
nissan,2017
cars-2018.csv
name,value
bmw,2018
tesla,2018
nissan,2018
cars.schema.json
{
"fields": [
{
"name": "name",
"type": "string"
},
{
"name": "value",
"type": "integer"
}
]
}
datapackage.json
{
"name": "datapackage",
"resources": [
{
"group": "cars",
"name": "cars-2017",
"path": "cars-2017.csv",
"profile": "tabular-data-resource",
"schema": "cars.schema.json"
},
{
"group": "cars",
"name": "cars-2018",
"path": "cars-2018.csv",
"profile": "tabular-data-resource",
"schema": "cars.schema.json"
}
]
}
Let's read the resources separately:
package = Package('datapackage.json')
package.get_resource('cars-2017').read(keyed=True) == [
{'name': 'bmw', 'value': 2017},
{'name': 'tesla', 'value': 2017},
{'name': 'nissan', 'value': 2017},
]
package.get_resource('cars-2018').read(keyed=True) == [
{'name': 'bmw', 'value': 2018},
{'name': 'tesla', 'value': 2018},
{'name': 'nissan', 'value': 2018},
]
On the other hand, these resources defined with a group: cars field. It means we can treat them as a group:
package = Package('datapackage.json')
package.get_group('cars').read(keyed=True) == [
{'name': 'bmw', 'value': 2017},
{'name': 'tesla', 'value': 2017},
{'name': 'nissan', 'value': 2017},
{'name': 'bmw', 'value': 2018},
{'name': 'tesla', 'value': 2018},
{'name': 'nissan', 'value': 2018},
]
We can use this approach when we need to save the data package to a storage, for example, to a SQL database. There is the merge_groups flag to enable groupping behaviour:
package = Package('datapackage.json')
package.save(storage='sql', engine=engine)
# SQL tables:
# - cars-2017
# - cars-2018
package.save(storage='sql', engine=engine, merge_groups=True)
# SQL tables:
# - cars
Working with Profile
A component to represent JSON Schema profile from Profiles Registry:
profile = Profile('data-package')
profile.name # data-package
profile.jsonschema # JSON Schema contents
try:
valid = profile.validate(descriptor)
except exceptions.ValidationError as exception:
for error in exception.errors:
# handle individual error
Working with Foreign Keys
The library supports foreign keys described in the Table Schema specification. It means if your data package descriptor use resources[].schema.foreignKeys property for some resources a data integrity will be checked on reading operations.
Consider we have a data package: