From 870d9bc7e923e67c09bdbcb32f4a56c48d4d5525 Mon Sep 17 00:00:00 2001 From: Adam Coddington Date: Sat, 18 May 2013 22:35:52 -0700 Subject: [PATCH] Adding support for downloading files from iCloud's ubiquity service. --- README.md | 28 +++++++++++++++++++++++++++- pyicloud/services/ubiquity.py | 10 ++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 1850d74..cac6ebe 100644 --- a/README.md +++ b/README.md @@ -125,7 +125,7 @@ You can access documents stored in your iCloud account by using the `files` prop ] ``` -And, you can access children and their children's children using the filename as an index: +You can access children and their children's children using the filename as an index: ```python >>> api.files['com~apple~Notes'] @@ -145,3 +145,29 @@ datetime.datetime(2012, 9, 13, 2, 26, 17) >>> api.files['com~apple~Notes']['Documents']['Some Document'].type u'file' ``` + +And when you have a file that you'd like to download, the `open` method will return a response object from which you can read the `content`. + +```python +>>> api.files['com~apple~Notes']['Documents']['Some Document'].open().content +'Hello, these are the file contents' +``` + +Note: the object returned from the above `open` method is a [response object](http://www.python-requests.org/en/latest/api/#classes) and the `open` method can accept any parameters you might normally use in a request using [requests](https://github.com/kennethreitz/requests). + +For example, if you know that the file you're opening has JSON content: + +```python +>>> api.files['com~apple~Notes']['Documents']['information.json'].open().json() +{'How much we love you': 'lots'} +>>> api.files['com~apple~Notes']['Documents']['information.json'].open().json()['How much we love you'] +'lots' +``` + +Or, if you're downloading a particularly large file, you may want to use the `stream` keyword argument, and read directly from the raw response object: + +```python +>>> download = api.files['com~apple~Notes']['Documents']['big_file.zip'].open(stream=True) +>>> with open('downloaded_file.zip', 'wb') as opened_file: + opened_file.write(download.read()) +``` diff --git a/pyicloud/services/ubiquity.py b/pyicloud/services/ubiquity.py index 5fce273..5ba0150 100644 --- a/pyicloud/services/ubiquity.py +++ b/pyicloud/services/ubiquity.py @@ -33,6 +33,13 @@ class UbiquityService(object): items = request.json()['item_list'] return [UbiquityNode(self, item) for item in items] + def get_file(self, id, **kwargs): + request = self.session.get( + self.get_node_url(id, 'file'), + **kwargs + ) + return request + @property def root(self): if not self._root: @@ -85,6 +92,9 @@ class UbiquityNode(object): def dir(self): return [child.name for child in self.get_children()] + def open(self, **kwargs): + return self.connection.get_file(self.item_id, **kwargs) + def get(self, name): return [child for child in self.get_children() if child.name == name][0]