Core API

You can use pyuploadcare in any Python project. At first you need assign your project keys to conf object. After that you will be able to do direct api calls or use api resources:

>>> import pyuploadcare
>>> pyuploadcare.conf.pub_key = '<your public key>'
>>> pyuploadcare.conf.secret = '<your private key>'
>>> f = pyuploadcare.File('6c5e9526-b0fe-4739-8975-72e8d5ee6342')
>>> f.cdn_url
https://ucarecdn.com/6c5e9526-b0fe-4739-8975-72e8d5ee6342/

File API Resource

class pyuploadcare.api_resources.File(cdn_url_or_file_id)

File resource for working with user-uploaded files.

It can take file UUID or group CDN url:

>>> file_ = File('a771f854-c2cb-408a-8c36-71af77811f3b')
>>> file_.cdn_url
https://ucarecdn.com/a771f854-c2cb-408a-8c36-71af77811f3b/
>>> print File('https://ucarecdn.com/a771f854-c2cb-408a-8c36-71af77811f3b/-/effect/flip/')
https://ucarecdn.com/a771f854-c2cb-408a-8c36-71af77811f3b/-/effect/flip/
uuid

File UUID [1], e.g. a771f854-c2cb-408a-8c36-71af77811f3b.

default_effects

String of default effects that is used by File.cdn_url, e.g. effect/flip/-/effect/mirror/.

class FileFromUrl(token)

Contains the logic around an upload from url.

It expects uploading token, for instance:

>>> ffu = FileFromUrl(token='a6a2db73-2aaf-4124-b2e7-039aec022e18')
>>> ffu.info()
{
    "status': "progress",
    "done": 226038,
    "total": 452076
}
>>> ffu.update_info()
{
    "status": "success",
    "file_id": "63f652fd-3f40-4b54-996c-f17dc7db5bf1",
    "is_stored": false,
    "done": 452076,
    "uuid": "63f652fd-3f40-4b54-996c-f17dc7db5bf1",
    "original_filename": "olympia.jpg",
    "is_image": true,
    "total": 452076,
    "size": 452076
}
>>> ffu.get_file()
<uploadcare.File 63f652fd-3f40-4b54-996c-f17dc7db5bf1>

But it could be failed:

>>> ffu.update_info()
{
    "status": "error",
    "error": "some error message"
}
get_file()

Returns File instance if upload is completed.

info()

Returns actual information about uploading as dict.

First time it makes API request to get information and keeps it for further using.

update_info()

Updates and returns information by requesting Uploadcare API.

wait(timeout=30, interval=0.3, until_ready=False)
File.cdn_path(effects=None)
File.cdn_url

Returns file’s CDN url.

Usage example:

>>> file_ = File('a771f854-c2cb-408a-8c36-71af77811f3b')
>>> file_.cdn_url
https://ucarecdn.com/a771f854-c2cb-408a-8c36-71af77811f3b/

You can set default effects:

>>> file_.default_effects = 'effect/flip/-/effect/mirror/'
>>> file_.cdn_url
https://ucarecdn.com/a771f854-c2cb-408a-8c36-71af77811f3b/-/effect/flip/-/effect/mirror/
classmethod File.construct_from(file_info)

Constructs File instance from file information.

For example you have result of /files/1921953c-5d94-4e47-ba36-c2e1dd165e1a/ API request:

>>> file_info = {
        # ...
        'uuid': '1921953c-5d94-4e47-ba36-c2e1dd165e1a',
        # ...
    }
>>> File.construct_from(file_info)
<uploadcare.File 1921953c-5d94-4e47-ba36-c2e1dd165e1a>
File.copy(effects=None, target=None)

Creates File copy

If target is None, copy file to Uploadcare storage otherwise copy to target associated with project. Add effects to self.default_effects if any.

File.datetime_removed()

Returns file’s remove aware datetime in UTC format.

It might do API request once because it depends on info().

File.datetime_stored()

Returns file’s store aware datetime in UTC format.

It might do API request once because it depends on info().

File.datetime_uploaded()

Returns file’s upload aware datetime in UTC format.

It might do API request once because it depends on info().

File.delete()

Deletes file by requesting Uploadcare API.

File.filename()

Returns original file name, e.g. "olympia.jpg".

It might do API request once because it depends on info().

File.info()

Returns all available file information as dict.

First time it makes API request to get file information and keeps it for further using.

File.is_image()

Returns True if the file is an image.

It might do API request once because it depends on info().

File.is_ready()

Returns True if the file is fully uploaded on S3.

It might do API request once because it depends on info().

File.is_removed()

Returns True if file is removed.

It might do API request once because it depends on info().

File.is_stored()

Returns True if file is stored.

It might do API request once because it depends on info().

File.mime_type()

Returns the file MIME type, e.g. "image/png".

It might do API request once because it depends on info().

File.size()

Returns the file size in bytes.

It might do API request once because it depends on info().

File.store()

Stores file by requesting Uploadcare API.

Uploaded files do not immediately appear on Uploadcare CDN. Let’s consider steps until file appears on CDN:

  • first file is uploaded into https://upload.uploadcare.com/;
  • after that file is available by API and its is_public, is_ready are False. Now you can store it;
  • is_ready will be True when file will be fully uploaded on S3.
File.update_info()

Updates and returns file information by requesting Uploadcare API.

classmethod File.upload(file_obj)

Uploads a file and returns File instance.

classmethod File.upload_from_url(url)

Uploads file from given url and returns FileFromUrl instance.

classmethod File.upload_from_url_sync(url, timeout=30, interval=0.3, until_ready=False)

Uploads file from given url and returns File instance.

File.uuid

File Group API Resource

class pyuploadcare.api_resources.FileGroup(cdn_url_or_group_id)

File Group resource for working with user-uploaded group of files.

It can take group id or group CDN url:

>>> file_group = FileGroup('0513dda0-582f-447d-846f-096e5df9e2bb~2')

You can iterate file_group or get File instance by key:

>>> [file_ for file_ in file_group]
[<uploadcare.File 6c5e9526-b0fe-4739-8975-72e8d5ee6342>, None]
>>> file_group[0]
<uploadcare.File 6c5e9526-b0fe-4739-8975-72e8d5ee6342>
>>> len(file_group)
2

But slicing is not supported because FileGroup is immutable:

>>> file_group[:]
TypeError: slicing is not supported

If file was deleted then you will get None:

>>> file_group[1]
None
id

Group id, e.g. 0513dda0-582f-447d-846f-096e5df9e2bb~2.

cdn_url

Returns group’s CDN url.

Usage example:

>>> file_group = FileGroup('0513dda0-582f-447d-846f-096e5df9e2bb~2')
>>> file_group.cdn_url
https://ucarecdn.com/0513dda0-582f-447d-846f-096e5df9e2bb~2/
classmethod construct_from(group_info)

Constructs FileGroup instance from group information.

classmethod create(files)

Creates file group and returns FileGroup instance.

It expects iterable object that contains File instances, e.g.:

>>> file_1 = File('6c5e9526-b0fe-4739-8975-72e8d5ee6342')
>>> file_2 = File('a771f854-c2cb-408a-8c36-71af77811f3b')
>>> FileGroup.create((file_1, file_2))
<uploadcare.FileGroup 0513dda0-6666-447d-846f-096e5df9e2bb~2>
datetime_created()

Returns file group’s create aware datetime in UTC format.

datetime_stored()

Returns file group’s store aware datetime in UTC format.

file_cdn_urls

Returns CDN urls of all files from group without API requesting.

Usage example:

>>> file_group = FileGroup('0513dda0-582f-447d-846f-096e5df9e2bb~2')
>>> file_group.file_cdn_urls[0]
'https://ucarecdn.com/0513dda0-582f-447d-846f-096e5df9e2bb~2/nth/0/'
info()

Returns all available group information as dict.

First time it makes API request to get group information and keeps it for further using.

is_stored()

Returns True if file is stored.

It might do API request once because it depends on info().

store()

Stores all group’s files by requesting Uploadcare API.

Uploaded files do not immediately appear on Uploadcare CDN.

update_info()

Updates and returns group information by requesting Uploadcare API.

File List API Resource

class pyuploadcare.api_resources.FileList(**kwargs)

List of File resources.

This class provides iteration over all uploaded files. You can specify:

  • since – a datetime object from which objects will be iterated;
  • until – a datetime object to which objects will be iterated;
  • limit – a total number of objects to be iterated. If not specified, all available objects are iterated;
  • storedTrue to include only stored files, False to exclude, None is default, will not exclude anything;
  • removedTrue to include only removed files, False to exclude, None will not exclude anything. The default is False.

If until is specified, the order of items will be reversed. It is impossible to specify since and until at the same time.

Files can’t be stored and removed at the same time, such query will always return an empty set. But files can be not stored and not removed (just uploaded files).

Usage example:

>>> for f in FileList(removed=None):
>>>     print f.datetime_uploaded()

Count objects:

>>> print('Number of stored files is', FileList(stored=True).count())
since
until
count
stored
removed
base_url = u'/files/'
constructor(file_info)

Constructs File instance from file information.

For example you have result of /files/1921953c-5d94-4e47-ba36-c2e1dd165e1a/ API request:

>>> file_info = {
        # ...
        'uuid': '1921953c-5d94-4e47-ba36-c2e1dd165e1a',
        # ...
    }
>>> File.construct_from(file_info)
<uploadcare.File 1921953c-5d94-4e47-ba36-c2e1dd165e1a>
filters = [(u'stored', None), (u'removed', False)]

Group List API Resource

class pyuploadcare.api_resources.GroupList(**kwargs)

List of FileGroup resources.

This class provides iteration over all groups for project. You can specify:

  • since – a datetime object from which objects will be iterated;
  • until – a datetime object to which objects will be iterated;
  • limit – a total number of objects to be iterated. If not specified, all available objects are iterated;

If until is specified, the order of items will be reversed. It is impossible to specify since and until at the same time.

Usage example:

>>> from datetime import datetime, timedelta
>>> for f in GroupList(since=datetime.now() - timedelta(weeks=1)):
>>>     print f.datetime_created()

Count objects:

>>> print('Number of groups is', GroupList().count())
since
until
count
base_url = u'/groups/'
constructor(group_info)

Constructs FileGroup instance from group information.

API Clients

Uploadcare REST client.

It is JSON REST request abstraction layer that is used by the pyuploadcare.api_resources.

pyuploadcare.api.rest_request(verb, path, data=None, timeout=<object object>, retry_throttled=<object object>)

Makes REST API request and returns response as dict.

It provides auth headers as well and takes settings from conf module.

Make sure that given path does not contain leading slash.

Usage example:

>>> rest_request('GET', 'files/?limit=10')
{
    'next': 'https://api.uploadcare.com/files/?limit=10&page=2',
    'total': 1241,
    'page': 1,
    'pages': 125,
    'per_page': 10,
    'previous': None,
    'results': [
        # ...
        {
            # ...
            'uuid': 1921953c-5d94-4e47-ba36-c2e1dd165e1a,
            # ...
        },
        # ...
    ]
}
pyuploadcare.api.uploading_request(verb, path, data=None, files=None, timeout=<object object>)

Makes Uploading API request and returns response as dict.

It takes settings from conf module.

Make sure that given path does not contain leading slash.

Usage example:

>>> file_obj = open('photo.jpg', 'rb')
>>> uploading_request('POST', 'base/', files={'file': file_obj})
{
    'file': '9b9f4483-77b8-40ae-a198-272ba6280004'
}
>>> File('9b9f4483-77b8-40ae-a198-272ba6280004')

Exceptions

exception pyuploadcare.exceptions.APIConnectionError(data=u'', *args, **kwargs)

Network communication with Uploadcare errors.

exception pyuploadcare.exceptions.APIError(data=u'', *args, **kwargs)

API errors, e.g. bad json.

exception pyuploadcare.exceptions.AuthenticationError(data=u'', *args, **kwargs)

Authentication with Uploadcare’s API errors.

exception pyuploadcare.exceptions.InvalidParamError(data=u'', *args, **kwargs)

Invalid parameters errors, e.g. invalid UUID

exception pyuploadcare.exceptions.InvalidRequestError(data=u'', *args, **kwargs)

Invalid service parameters errors, e.g status 404

exception pyuploadcare.exceptions.ThrottledRequestError(response)

Raised when request was throttled.

exception pyuploadcare.exceptions.TimeoutError(data=u'', *args, **kwargs)

Timed out errors.

It raises when user wants to wait the result of api requests, e.g.:

$ ucare store --wait 6c5e9526-b0fe-4739-8975-72e8d5ee6342
exception pyuploadcare.exceptions.UploadError(data=u'', *args, **kwargs)

Upload errors.

It raises when user wants to wait the result of:

$ ucare upload_from_url --wait http://path.to/file.jpg
exception pyuploadcare.exceptions.UploadcareException(data=u'', *args, **kwargs)

Base exception class of library.

[1]Universally unique identifier according to RFC 4122.