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/
-
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 a File Copy on Uploadcare or Custom Storage.
File.copy method is deprecated and will be removed in 4.0.0. Please use create_local_copy and create_remote_copy instead.
- Args:
- effects:
- Adds CDN image effects. If
self.default_effects
property is set effects will be combined with default effects.
- target:
- Name of a custom storage connected to your project. Uploadcare storage is used if target is absent.
-
File.
create_local_copy
(effects=None, store=None)¶ Creates a Local File Copy on Uploadcare Storage.
- Args:
- effects:
- Adds CDN image effects. If
self.default_effects
property is set effects will be combined with default effects.
- store:
- If
store
option is set to False the copy of your file will be deleted in 24 hour period after the upload. Works only if autostore is enabled in the project.
-
File.
create_remote_copy
(target, effects=None, make_public=None, pattern=None)¶ Creates file copy in remote storage.
- Args:
- target:
- Name of a custom storage connected to the project.
- effects:
- Adds CDN image effects to
self.default_effects
if any.
- make_public:
- To forbid public from accessing your files on the storage set
make_public
option to be False. Default value is None. Files have public access by default.
- pattern:
- Specify
pattern
option to set S3 object key name. Takes precedence over pattern set in project settings. If neither is specified defaults to ${uuid}/${filename}${effects}${ext}.
For more information on each of the options above please refer to REST API docs https://uploadcare.com/documentation/rest/#file.
Following example copies a file to custom storage named
samplefs
:>>> file = File('e8ebfe20-8c11-4a94-9b40-52ecad7d8d1a') >>> file.create_remote_copy(target='samplefs', >>> make_public=True, >>> pattern='${uuid}/${filename}${ext}')
Now custom storage
samplefs
contains publicly available file with original filename billmurray.jpg in in the directory namede8ebfe20-8c11-4a94-9b40-52ecad7d8d1a
.
-
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
areFalse
. Now you can store it; is_ready
will beTrue
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, store=None)¶ Uploads a file and returns
File
instance.- Args:
file_obj: file object to upload to
- store (Optional[bool]): Should the file be automatically stored
upon upload. Defaults to None. - False - do not store file - True - store file (can result in error if autostore
is disabled for project)
- None - use project settings
- Returns:
File
instance
-
classmethod
File.
upload_from_url
(url, store=None, filename=None)¶ Uploads file from given url and returns
FileFromUrl
instance.- Args:
url (str): URL of file to upload to
- store (Optional[bool]): Should the file be automatically stored
upon upload. Defaults to None. - False - do not store file - True - store file (can result in error if autostore
is disabled for project)
- None - use project settings
- filename (Optional[str]): Name of the uploaded file. If this not
specified the filename will be obtained from response headers or source URL. Defaults to None.
- Returns:
FileFromUrl
instance
-
classmethod
File.
upload_from_url_sync
(url, timeout=30, interval=0.3, until_ready=False, store=None, filename=None)¶ Uploads file from given url and returns
File
instance.- Args:
url (str): URL of file to upload to
- store (Optional[bool]): Should the file be automatically stored
upon upload. Defaults to None. - False - do not store file - True - store file (can result in error if autostore
is disabled for project)
- None - use project settings
- filename (Optional[str]): Name of the uploaded file. If this not
specified the filename will be obtained from response headers or source URL. Defaults to None.
- timeout (Optional[int]): seconds to wait for successful upload.
Defaults to 30.
- interval (Optional[float]): interval between upload status checks.
Defaults to 0.3.
- until_ready (Optional[bool]): should we wait until file is
available via CDN. Defaults to False.
- Returns:
File
instance- Raises:
TimeoutError
if file wasn’t uploaded in time
-
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 getFile
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
(*args, **kwargs)¶ List of File resources.
This class provides iteration over all uploaded files.
You can specify:
starting_point
– a starting point for filtering files. It is reflects afrom
parameter from REST API.ordering
– a string with name of the field what must be used for sorting files. The actual list of supported fields you can find in documentation: http://uploadcare.com/documentation/rest/#file-fileslimit
– a total number of objects to be iterated. If not specified, all available objects are iterated;request_limit
– a number of objects retrieved per request (page). Usually, you don’t need worry about this parameter.stored
–True
to include only stored files,False
to exclude,None
is default, will not exclude anything;removed
–True
to include only removed files,False
to exclude,None
will not exclude anything. The default isFalse
.
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())
-
api_url
(**qs)¶
-
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>
-
datetime_ordering_fields
= (u'', u'datetime_uploaded')¶
Group List API Resource¶
-
class
pyuploadcare.api_resources.
GroupList
(starting_point=None, ordering=None, limit=None, request_limit=None)¶ List of FileGroup resources.
This class provides iteration over all groups for project. You can specify:
starting_point
– a starting point for filtering groups. It is reflects afrom
parameter from the REST API.ordering
– a string with name of the field what must be used for sorting files. The actual list of supported fields you can find in documentation: https://uploadcare.com/documentation/rest/#group-groupslimit
– a total number of objects to be iterated. If not specified, all available objects are iterated;request_limit
– a number of objects retrieved per request (page). Usually, you don’t need worry about this parameter.
Usage example:
>>> from datetime import datetime, timedelta >>> last_week = datetime.now() - timedelta(weeks=1) >>> for f in GroupList(starting_point=last_week): >>> print(f.datetime_created())
Count objects:
>>> print('Number of groups is', GroupList().count())
-
base_url
= u'/groups/'¶
-
constructor
(group_info)¶ Constructs
FileGroup
instance from group information.
-
datetime_ordering_fields
= (u'', u'datetime_created')¶
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. |