Adding support for downloading files from iCloud's ubiquity service.

This commit is contained in:
Adam Coddington 2013-05-18 22:35:52 -07:00
parent 1d45ad9e7d
commit 870d9bc7e9
2 changed files with 37 additions and 1 deletions

View file

@ -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 ```python
>>> api.files['com~apple~Notes'] >>> 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 >>> api.files['com~apple~Notes']['Documents']['Some Document'].type
u'file' 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())
```

View file

@ -33,6 +33,13 @@ class UbiquityService(object):
items = request.json()['item_list'] items = request.json()['item_list']
return [UbiquityNode(self, item) for item in items] 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 @property
def root(self): def root(self):
if not self._root: if not self._root:
@ -85,6 +92,9 @@ class UbiquityNode(object):
def dir(self): def dir(self):
return [child.name for child in self.get_children()] 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): def get(self, name):
return [child for child in self.get_children() if child.name == name][0] return [child for child in self.get_children() if child.name == name][0]