Core API

Initialization

You can use pyuploadcare in any Python project. You need to pass your project keys to Uploadcare client:

from pyuploadcare import Uploadcare
uploadcare = Uploadcare(public_key='<your public key>', secret_key='<your private key>')

Uploading files

Upload single file. File.upload method can accept file object or URL. Depending of file object size direct or multipart upload method will be chosen:

with open('file.txt') as file_object:
    ucare_file: File = uploadcare.upload(file_object)

Upload file from url:

ucare_file: File = uploadcare.upload("https://github.githubassets.com/images/modules/logos_page/Octocat.png")

Upload multiple files. Direct upload method is used:

file1 = open('file1.txt')
file2 = open('file2.txt')
ucare_files: List[File] = uploadcare.upload_files([file1, file2])

Send single file via multipart upload:

with open('file.txt') as file_object:
    ucare_file: File = uploadcare.upload(file_object)

Uploadcare.upload method accepts optional callback function to track uploading progress. Example of using callback function for printing progress:

>>> def print_progress(info: UploadProgress):
...     print(f'{info.done}/{info.total} B')

>>> # multipart upload is used
>>> with open('big_file.jpg', 'rb') as fh:
...    uploadcare.upload(fh, callback=print_progress)
0/11000000 B
5242880/11000000 B
10485760/11000000 B
11000000/11000000 B

>>> # upload from url is used
>>> uploadcare.upload("https://github.githubassets.com/images/modules/logos_page/Octocat.png", callback=print_progress)
32590/32590 B

>>> # direct upload is used. Callback is called just once after successful upload
>>> with open('small_file.jpg', 'rb') as fh:
...     uploadcare.upload(fh, callback=print_progress)
56780/56780 B

List files

Get list of files:

files: FileList = uploadcare.list_files(stored=True, limit=10)
for file in files:
    print(file.info)

Retrieve files

Get existing file:

file: File = uploadcare.file("740e1b8c-1ad8-4324-b7ec-112c79d8eac2")
print(file.info)

Store files

Store single file:

file: File = uploadcare.file("740e1b8c-1ad8-4324-b7ec-112c79d8eac2")
file.store()

Store multiple files:

files = [
    '6c5e9526-b0fe-4739-8975-72e8d5ee6342',
    'a771f854-c2cb-408a-8c36-71af77811f3b'
]
uploadcare.store_files(files)

Delete files

Delete single file:

file: File = uploadcare.file("740e1b8c-1ad8-4324-b7ec-112c79d8eac2")
file.delete()

Delete multiple files:

files = [
    '6c5e9526-b0fe-4739-8975-72e8d5ee6342',
    'a771f854-c2cb-408a-8c36-71af77811f3b'
]
uploadcare.delete_files(files)

Video conversion

Uploadcare can encode video files from all popular formats, adjust their quality, format and dimensions, cut out a video fragment, and generate thumbnails via REST API.

After each video file upload you obtain a file identifier in UUID format. Then you can use this file identifier to convert your video in multiple ways:

file = uploadcare.file('740e1b8c-1ad8-4324-b7ec-112c79d8eac2')
transformation = (
    VideoTransformation()
        .format(Format.mp4)
        .size(width=640, height=480, resize_mode=ResizeMode.add_padding)
        .quality(Quality.lighter)
        .cut(start_time='2:30.535', length='2:20.0')
        .thumbs(10)
)
converted_file: File = file.convert(transformation)

or you can use API directly to convert single or multiple files:

transformation = VideoTransformation().format(VideoFormat.webm).thumbs(2)
paths: List[str] = [
    transformation.path("740e1b8c-1ad8-4324-b7ec-112c79d8eac2"),
]

response = uploadcare.video_convert_api.convert(paths)
video_convert_info = response.result[0]
converted_file = uploadcare.file(video_convert_info.uuid)

video_convert_status = uploadcare.video_convert_api.status(video_convert_info.token)

Document Conversion

Uploadcare allows converting documents to the following target formats: doc, docx, xls, xlsx, odt, ods, rtf, txt, pdf, jpg, png. Document Conversion works via our REST API.

After each document file upload you obtain a file identifier in UUID format. Then you can use this file identifier to convert your document to a new format:

file = uploadcare.file('0e1cac48-1296-417f-9e7f-9bf13e330dcf')
transformation = DocumentTransformation().format(DocumentFormat.pdf)
converted_file: File = file.convert(transformation)

or create an image of a particular page (if using image format):

file = uploadcare.file('5dddafa0-a742-4a51-ac40-ae491201ff97')
transformation = DocumentTransformation().format(DocumentFormat.png).page(1)
converted_file: File = file.convert(transformation)

or you can use API directly to convert single or multiple files:

transformation = DocumentTransformation().format(DocumentFormat.pdf)

paths: List[str] = [
    transformation.path("0e1cac48-1296-417f-9e7f-9bf13e330dcf"),
]

response = uploadcare.document_convert_api.convert([path])
document_convert_info = response.result[0]
converted_file = uploadcare.file(document_convert_info.uuid)

document_convert_status = uploadcare.document_convert_api.status(document_convert_info.token)

Image transformations

Uploadcare allows to apply image transformations to files. File.cdn_url attribute returns CDN url:

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

You can set default effects by string:

>>> file_.set_effects('effect/flip/-/effect/mirror/')
>>> file_.cdn_url
https://ucarecdn.com/a771f854-c2cb-408a-8c36-71af77811f3b/-/effect/flip/-/effect/mirror/

or by image transformation builder:

>>> file_.set_effects(ImageTransformation().grayscale().flip())
>>> file_.cdn_url
https://ucarecdn.com/a771f854-c2cb-408a-8c36-71af77811f3b/-/grayscale/-/flip/

Create file group

Create file group:

file_1: File = uploadcare.file('6c5e9526-b0fe-4739-8975-72e8d5ee6342')
file_2: File = uploadcare.file('a771f854-c2cb-408a-8c36-71af77811f3b')
file_group: FileGroup = uploadcare.create_file_group([file_1, file_2])

Retreive file group

Get file group:

file_group: FileGroup = uploadcare.file_group('0513dda0-582f-447d-846f-096e5df9e2bb~2')
print(file_group.info())

Store file group

Stores all group’s files:

file_group: FileGroup = uploadcare.file_group('0513dda0-582f-447d-846f-096e5df9e2bb~2')
file_group.store()

List file groups

List file groups:

file_groups: List[FileGroup] = uploadcare.list_file_groups(limit=10)
for file_group in file_groups:
    print(file_group.info)

Create webhook

Create a webhook:

webhook: Webhook = uploadcare.create_webhook("https://path/to/webhook")

Create a webhook with a signing secret:

webhook = uploadcare.create_webhook(
    target_url="https://path/to/webhook",
    signing_secret="7kMVZivndx0ErgvhRKAr",
)

List webhooks

List webhooks:

webhooks: List[Webhook] = list(uploadcare.list_webhooks(limit=10))

Update webhook

Update a webhook:

webhook: Webhook = uploadcare.update_webhook(webhook_id, is_active=False)

Update a webhook’s signing secret:

webhook: Webhook = uploadcare.update_webhook(webhook_id, signing_secret="7kMVZivndx0ErgvhRKAr")

Delete webhook

Delete a webhook:

uploadcare.delete_webhook(webhook_id)

Get project info

Get project info:

project_info: ProjectInfo = uploadcare.get_project_info()

Secure delivery

You can use your own custom domain and CDN provider for deliver files with authenticated URLs (see original documentation).

Generate secure for file:

from pyuploadcare import Uploadcare
from pyuploadcare.secure_url import AkamaiSecureUrlBuilder

secure_url_bulder = AkamaiSecureUrlBuilder("your cdn>", "<your secret for token generation>")

uploadcare = Uploadcare(
    public_key='<your public key>',
    secret_key='<your private key>',
    secure_url_builder=secure_url_bulder,
)

secure_url = uploadcare.generate_secure_url('52da3bfc-7cd8-4861-8b05-126fef7a6994')

Generate secure for file with transformations:

secure_url = uploadcare.generate_secure_url(
    '52da3bfc-7cd8-4861-8b05-126fef7a6994/-/resize/640x/other/transformations/'
)

Uploadcare client

class pyuploadcare.client.Uploadcare(public_key: Optional[str, None] = None, secret_key: Optional[str, None] = None, api_base='https://api.uploadcare.com/', upload_base='https://upload.uploadcare.com/', cdn_base='https://ucarecdn.com/', api_version='0.6', signed_uploads=True, signed_uploads_ttl=60, verify_api_ssl=True, verify_upload_ssl=True, retry_throttled=1, user_agent_extension=None, timeout=<object object>, batch_chunk_size=500, multipart_min_file_size=10485760, multipart_chunk_size=5242880, auth_class: Type[pyuploadcare.api.auth.UploadcareAuth] = <class 'pyuploadcare.api.auth.UploadcareAuth'>, secure_url_builder: Optional[pyuploadcare.secure_url.BaseSecureUrlBuilder, None] = None)

Uploadcare client.

Initialize client:

>>> uploadcare = Uploadcare(public_key='<public-key>', secret_key='<secret-key>')
Args:
  • public_key: Public key to access Uploadcare API.
  • secret_key: Secret ket to access Uploadcare API.
  • api_base: Rest API base url.
  • upload_base: Upload API base url.
  • cdn_base: CDN base url.
  • api_version: API version.
  • signed_uploads: Enable signed uploads.
  • signed_uploads_ttl: Signed uploads signature timeout in seconds.
  • verify_api_ssl: Verify Rest API SSL certificate.
  • verify_upload_ssl: Verify Upload API SSL certificate.
  • retry_throttled: Amount of retries after throttling header received.
  • user_agent_extension: Extra suffix to user agent to identify client.
  • timeout: HTTP requests timeout. If not set, default socket timeout is used.
  • batch_chunk_size: Amount of files to process at once in batch store and delete requests.
  • multipart_min_file_size: Mininum file size to use multipart uploading.
  • multipart_chunk_size: Chunk size in bytes for multipart uploading.
  • auth_class: Authentication class to use for API.
  • secure_url_builder: URL builder for secure delivery.
create_file_group(files: List[pyuploadcare.resources.file.File]) → pyuploadcare.resources.file_group.FileGroup

Creates file group and returns FileGroup instance.

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

>>> uploadcare = Uploadcare(public_key='<public-key>', secret_key='<secret-key>')
>>> file_1 = uploadcare.file('6c5e9526-b0fe-4739-8975-72e8d5ee6342')
>>> file_2 = uploadcare.file('a771f854-c2cb-408a-8c36-71af77811f3b')
>>> uploadcare.create_file_group([file_1, file_2])
<uploadcare.FileGroup 0513dda0-6666-447d-846f-096e5df9e2bb~2>
create_webhook(target_url: str, event='file.uploaded', is_active=True, signing_secret=None) → pyuploadcare.api.entities.Webhook

Create and subscribe to a webhook.

delete_files(files: Iterable[Union[str, File]]) → None

Deletes multiple files by requesting Uploadcare API.

Usage example:

>>> uploadcare = Uploadcare(public_key='<public-key>', secret_key='<secret-key>')
>>> files = [
... '6c5e9526-b0fe-4739-8975-72e8d5ee6342',
... 'a771f854-c2cb-408a-8c36-71af77811f3b'
... ]
>>> uploadcare.delete_files(files)
Args:
  • files:
    List of file UUIDs, CND urls or File instances.
delete_webhook(webhook_id: Union[pyuploadcare.api.entities.Webhook, int]) → None

Unsubscribe and delete a webhook.

file(cdn_url_or_file_id: Union[str, uuid.UUID], file_info: Optional[Dict[str, Any], None] = None) → pyuploadcare.resources.file.File

File resource for working with user-uploaded files.

It can take file UUID or group CDN url:

>>> file_ = uploadcare.file('a771f854-c2cb-408a-8c36-71af77811f3b')
>>> file_.cdn_url
https://ucarecdn.com/a771f854-c2cb-408a-8c36-71af77811f3b/
>>> print uploadcare.file(
...    'https://ucarecdn.com/a771f854-c2cb-408a-8c36-71af77811f3b/-/effect/flip/')
https://ucarecdn.com/a771f854-c2cb-408a-8c36-71af77811f3b/-/effect/flip/
file_group(group_id: str, group_info: Optional[Dict[str, Any], None] = None) → pyuploadcare.resources.file_group.FileGroup

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

It can take group id or group CDN url:

>>> file_group = uploadcare.file_group('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
generate_secure_url(uuid: Union[str, uuid.UUID]) → str

Generate authenticated URL.

get_project_info() → pyuploadcare.api.entities.ProjectInfo

Get info about account project.

list_file_groups(starting_point=None, ordering=None, limit: Optional[int, None] = None, request_limit: Optional[int, None] = None)

List file groups.

Return GroupList instance providing iteration over all groups for project.

Args:
  • starting_point – a starting point for filtering groups. It is reflects a from 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.
  • limit – 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 uploadcare.list_file_groups(starting_point=last_week):
>>>     print(f.datetime_created)

Count objects:

>>> print('Number of groups is', uploadcare.list_file_groups().count())
list_files(starting_point=None, ordering=None, limit: Optional[int, None] = None, request_limit: Optional[int, None] = None, stored: Optional[bool, None] = None, removed: Optional[bool, None] = None) → pyuploadcare.resources.file_list.FileList

List files.

Returns FileList instance providing iteration over all uploaded files.

Args:m
  • starting_point – a starting point for filtering files. It is reflects a from 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-files
  • limit – 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.
  • 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.

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 uploadcare.list_files(removed=None):
>>>     print(f.datetime_uploaded)

Count objects:

>>> print('Number of stored files is', uploadcare.list_files(stored=True).count())
list_webhooks(limit=None) → Iterable[pyuploadcare.api.entities.Webhook]

List of project webhooks.

multipart_upload(file_obj: IO, store: Optional[bool, None] = None, size: Optional[int, None] = None, mime_type: Optional[str, None] = None, callback: Optional[Callable[[pyuploadcare.resources.file.UploadProgress], Any], None] = None) → pyuploadcare.resources.file.File

Upload file straight to s3 by chunks.

Multipart Uploads are useful when you are dealing with files larger than 100MB or explicitly want to use accelerated uploads.

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
  • size (Optional[int]): file size in bytes.

    If not set, it is calculated by os.fstat

  • mime_type (Optional[str]): file mime type.

    If not set, it is guessed from filename extension.

  • callback (Optional[Callable[[UploadProgress], Any]]): Optional callback

    accepting UploadProgress to track uploading progress.

Returns:
File instance
store_files(files: Iterable[Union[str, File]]) → None

Stores multiple files by requesting Uploadcare API.

Usage example:

>>> uploadcare = Uploadcare(public_key='<public-key>', secret_key='<secret-key>')
>>> files = [
... '6c5e9526-b0fe-4739-8975-72e8d5ee6342',
... 'a771f854-c2cb-408a-8c36-71af77811f3b'
... ]
>>> uploadcare.store_files(files)
Args:
  • files:
    List of file UUIDs, CND urls or File instances.
update_webhook(webhook_id: Union[pyuploadcare.api.entities.Webhook, int], target_url=None, event=None, is_active=None, signing_secret=None) → pyuploadcare.api.entities.Webhook

Update webhook attributes.

upload(file_handle: Union[IO, str], store=None, size: Optional[int, None] = None, callback: Optional[Callable[[pyuploadcare.resources.file.UploadProgress], Any], None] = None) → pyuploadcare.resources.file.File

Uploads a file and returns File instance.

Method can accept file object or URL. Depending of file object size direct or multipart upload method will be chosen.

Upload from url:

>>> uploadcare = Uploadcare(public_key='<public-key>', secret_key='<secret-key>')
>>> file: File = uploadcare.upload("https://shorturl.at/fAX28")

Upload small file, direct upload is used:

>>> fh = open('small_file.jpg', 'rb')
>>> file: File = uploadcare.upload(fh)

Upload big file, multipart upload is used:

>>> with open('big_file.mp4', 'rb') as fh:
>>>     file: File = uploadcare.upload(fh)

To track uploading progress you can pass optional callback function:

>>> def print_progress(info: UploadProgress):
...     print(f'{info.done}/{info.total} B')
>>>
>>> with open('big_file.mp4', 'rb') as fh:
...    file: File = uploadcare.upload(fh, callback=print_progress)
0/11000000 B
5242880/11000000 B
10485760/11000000 B
11000000/11000000 B
Args:
  • file_handle: file object or url to upload to. If file object

    is passed, File.upload_files (direct upload) or File.multipart_upload (multipart upload) will be used. If file URL is passed, File.upload_from_url_sync will be used for uploading.

  • 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
  • size (Optional[int]): file size in bytes.

    If not set, it is calculated by os.fstat. Used for multipart uploading.

  • callback (Optional[Callable[[UploadProgress], Any]]): Optional callback

    accepting UploadProgress to track uploading progress.

Returns:
File instance
upload_files(file_objects: List[IO], store: Optional[bool, None] = None) → List[pyuploadcare.resources.file.File]

Upload multiple files using direct upload.

It support files smaller than 100MB only. If you want to upload larger files, use Multipart Uploads.

Args:
  • file_objects: list of file objects 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
upload_from_url(url, store=None, filename=None) → pyuploadcare.resources.file.FileFromUrl

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
upload_from_url_sync(url, timeout=30, interval=0.3, until_ready=False, store=None, filename=None, callback: Optional[Callable[[pyuploadcare.resources.file.UploadProgress], Any], None] = None) → pyuploadcare.resources.file.File

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.

  • callback (Optional[Callable[[UploadProgress], Any]]): Optional callback

    accepting UploadProgress to track uploading progress.

Returns:
File instance
Raises:
TimeoutError if file wasn’t uploaded in time

Resources

File API Resource

class pyuploadcare.resources.file.File(cdn_url_or_file_id, client: Uploadcare)

File resource for working with user-uploaded files.

It can take file UUID or group CDN url:

>>> file_ = uploadcare.file('a771f854-c2cb-408a-8c36-71af77811f3b')
>>> file_.cdn_url
https://ucarecdn.com/a771f854-c2cb-408a-8c36-71af77811f3b/
>>> print uploadcare.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/.

cdn_path(effects: Union[str, pyuploadcare.transformations.image.ImageTransformation, None] = None)

Returns CDN path with applied effects.

Usage example:

>>> >>> file = File('a771f854-c2cb-408a-8c36-71af77811f3b')
>>> file.cdn_path()
a771f854-c2cb-408a-8c36-71af77811f3b/
>>> file.cdn_path('effect/flip/-/effect/mirror/')
a771f854-c2cb-408a-8c36-71af77811f3b/-/effect/flip/-/effect/mirror/
>>> image_transforamtion = (
...     ImageTransformation()
...     .smart_resize(440, 600)
...     .quality(ImageQuality.smart)
... )
>>> file.cdn_path(image_transforamtion)
a771f854-c2cb-408a-8c36-71af77811f3b/-/smart_resize/440x600/-/quality/smart/
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 by string:

>>> file_.set_effects('effect/flip/-/effect/mirror/')
>>> file_.cdn_url
https://ucarecdn.com/a771f854-c2cb-408a-8c36-71af77811f3b/-/effect/flip/-/effect/mirror/

or by image transformation builder:

>>> file_.set_effects(ImageTransformation().grayscale().flip())
>>> file_.cdn_url
https://ucarecdn.com/a771f854-c2cb-408a-8c36-71af77811f3b/-/grayscale/-/flip/
convert(transformation: Union[pyuploadcare.transformations.video.VideoTransformation, pyuploadcare.transformations.document.DocumentTransformation], store: Optional[bool, None] = None) → pyuploadcare.resources.file.File

Convert video or document and return converted file.

Convert video:

>>> file = uploadcare.file('740e1b8c-1ad8-4324-b7ec-112c79d8eac2')
>>> transformation = (
...     VideoTransformation()
...         .format(Format.mp4)
...         .size(width=640,height=480, resize_mode=ResizeMode.add_padding)
...         .quality(Quality.lighter)
...         .cut(start_time='2:30.535', length='2:20.0')
...         .thumbs(10)
... )
>>> converted_file: File = file.convert(transformation)
>>> converted_file.thumbnails_group_uuid
e16536ff-7250-4376-81a4-596e3fef37b0~10

Convert document:

>>> file = File('740e1b8c-1ad8-4324-b7ec-112c79d8eac2')
>>> transformation = DocumentTransformation().format(DocumentFormat.pdf)
>>> converted_file: File = file.convert(transformation)
Arguments:
  • transformation (Union[VideoTransformation, Documenttransformation]): transformation
    path builder with configured parameters. Depending on type video or document conversion will be performed.
  • store (Optional[bool]): Should the file be automatically stored. Defaults to None.
    • False - do not store file
    • True - store file
    • None - use project settings
convert_document(transformation: Union[str, pyuploadcare.transformations.document.DocumentTransformation], store: Optional[bool, None] = None) → pyuploadcare.resources.file.File

Convert document and return converted file instance.

Arguments:
  • transformation (DocumentTransformation): transformation path builder
    with configured parameters.
  • store (Optional[bool]): Should the file be automatically stored. Defaults to None.
    • False - do not store file
    • True - store file
    • None - use project settings
convert_video(transformation: Union[str, pyuploadcare.transformations.video.VideoTransformation], store: Optional[bool, None] = None) → pyuploadcare.resources.file.File

Convert video and return converted file instance.

Arguments:
  • transformation (VideoTransformation): transformation path builder
    with configured parameters.
  • store (Optional[bool]): Should the file be automatically stored. Defaults to None.
    • False - do not store file
    • True - store file
    • None - use project settings
copy(effects: Union[str, pyuploadcare.transformations.image.ImageTransformation, None] = 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.
create_local_copy(effects: Union[str, pyuploadcare.transformations.image.ImageTransformation, None] = None, store=False) → pyuploadcare.resources.file.File

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.
create_remote_copy(target, effects: Union[str, pyuploadcare.transformations.image.ImageTransformation, None] = None, make_public=None, pattern=None) → str

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/docs/api_reference/rest/accessing_files/.

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 named e8ebfe20-8c11-4a94-9b40-52ecad7d8d1a.

datetime_removed

Returns file’s remove aware datetime in UTC format.

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

datetime_stored

Returns file’s store aware datetime in UTC format.

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

datetime_uploaded

Returns file’s upload aware datetime in UTC format.

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

delete() → None

Deletes file by requesting Uploadcare API.

filename

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

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

info

Returns all available file information as dict.

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

is_image

Returns True if the file is an image.

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

is_ready

Returns True if the file is fully uploaded on S3.

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

is_removed

Returns True if file is removed.

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

is_stored

Returns True if file is stored.

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

mime_type

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

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

set_effects(effects: Union[str, pyuploadcare.transformations.image.ImageTransformation, None] = None) → None
size

Returns the file size in bytes.

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

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.
thumbnails_group_uuid = None
update_info()

Updates and returns file information by requesting Uploadcare API.

uuid

FileFromUrl API Resource

class pyuploadcare.resources.file.FileFromUrl(token, client: Uploadcare)

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.

File Group API Resource

class pyuploadcare.resources.file_group.FileGroup(cdn_url_or_group_id: str, client: Uploadcare)

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

It can take group id or group CDN url:

>>> file_group = uploadcare.file_group('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 = uploadcare.file_group('0513dda0-582f-447d-846f-096e5df9e2bb~2')
>>> file_group.cdn_url
https://ucarecdn.com/0513dda0-582f-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 = uploadcare.file_group('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.resources.file_list.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 a from 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-files
  • limit – 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.
  • 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.

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 uploadcare.list_files(removed=None):
>>>     print(f.datetime_uploaded)

Count objects:

>>> print('Number of stored files is', uploadcare.list_files(stored=True).count())
constructor_name = 'file'
datetime_ordering_fields = ('', 'datetime_uploaded')
query_parameters(**parameters)
resource_api
resource_id_field = 'uuid'

Group List API Resource

class pyuploadcare.resources.group_list.GroupList(client: Uploadcare, 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 a from 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/docs/api_reference/rest/accessing_groups/#properties
  • limit – 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 uploadcare.list_file_groups(starting_point=last_week):
>>>     print(f.datetime_created)

Count objects:

>>> print('Number of groups is', uploadcare.list_file_groups().count())
constructor_name = 'file_group'
datetime_ordering_fields = ('', 'datetime_created')
resource_api
resource_id_field = 'id'

Exceptions

exception pyuploadcare.exceptions.APIConnectionError(message: str)

Network communication with Uploadcare errors.

exception pyuploadcare.exceptions.APIError(message: str)

API errors, e.g. bad json.

exception pyuploadcare.exceptions.AuthenticationError(message: str)

Authentication with Uploadcare’s API errors.

exception pyuploadcare.exceptions.DefaultResponseClassNotDefined
exception pyuploadcare.exceptions.InvalidParamError(message: str)

Invalid parameters errors, e.g. invalid UUID

exception pyuploadcare.exceptions.InvalidRequestError(message: str)

Invalid service parameters errors, e.g status 404

exception pyuploadcare.exceptions.ThrottledRequestError(response)

Raised when request was throttled.

exception pyuploadcare.exceptions.TimeoutError(message: str)

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(message: str)

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(message: str)
[1]Universally unique identifier according to RFC 4122.