===============
LIBRARY RULES
===============
From library maintainers:
- Create clients with pyuploadcare.Uploadcare using Uploadcare public and secret API keys.
- Keep Uploadcare secret keys in server-side code or environment-backed settings; never expose them to browsers.
- Use pyuploadcare.dj with the UPLOADCARE Django setting when integrating File Uploader widgets or model fields.
- Prefer resource methods on Uploadcare, File, and FileGroup for uploads, storage, deletion, metadata, conversions, and webhooks.
- Use transformation builder classes from pyuploadcare.transformations instead of hand-writing CDN paths when possible.
### Install PyUploadcare from Source
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/install.md
Install pyuploadcare after cloning the repository by running pip install in the project directory.
```bash
pip install .
```
--------------------------------
### Install PyUploadcare with Django Extras
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/install.md
Install pyuploadcare with additional dependencies for Django projects.
```bash
pip install pyuploadcare[django]
```
--------------------------------
### Install PyUploadcare with Pip
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/install.md
Use this command to install the base pyuploadcare package.
```bash
pip install pyuploadcare
```
--------------------------------
### Run Full Test Suite Locally
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/testing.md
Install the 'act' utility to run the full suite of tests locally, mimicking the behavior of Github Actions workflows. This ensures comprehensive testing across different Python and Django versions.
```console
make test_with_github_actions
```
--------------------------------
### Run Tests with GitHub Actions Locally
Source: https://github.com/uploadcare/pyuploadcare/blob/main/README.md
To run the full suite of tests locally using GitHub Actions workflows, install the 'act' utility and execute the provided command.
```make
test_with_github_actions
```
--------------------------------
### Get Project Information
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Retrieve general information about your Uploadcare project. This includes details like project name, plan, and storage usage.
```python
project_info: ProjectInfo = uploadcare.get_project_info()
```
--------------------------------
### Get Uploaded File Information
Source: https://github.com/uploadcare/pyuploadcare/blob/main/README.md
Fetch and print detailed information about an uploaded file, including its metadata, dimensions, and timestamps. Requires importing `pprint` for formatted output.
```python
from pprint import pprint
pprint(ucare_file.info)
```
--------------------------------
### Including Uploadcare Widget Assets
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/django-widget.md
Include the necessary CSS and JavaScript for the Uploadcare widget from a CDN. This example shows how to define custom components.
```html
```
--------------------------------
### Clone PyUploadcare Repository
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/install.md
Clone the pyuploadcare repository from GitHub to get the source code.
```bash
git clone git://github.com/uploadcare/pyuploadcare.git
```
--------------------------------
### Retrieve All File Metadata
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Get all metadata associated with a file by providing its unique identifier.
```python
file_metadata = uploadcare.metadata_api.get_all_metadata(file_id)
```
--------------------------------
### Get Secure URL Token
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Generates only the token part of a secure URL for a file.
```APIDOC
## Get Secure URL Token
### Description
Generates only the token part of a secure URL for a file.
### Method
`uploadcare.get_secure_url_token`
### Parameters
- **file_uuid** (string) - Required - The UUID of the file.
### Request Example
```python
token = uploadcare.get_secure_url_token('52da3bfc-7cd8-4861-8b05-126fef7a6994')
```
### Response
- **token** (string) - The generated secure URL token.
```
--------------------------------
### Get Specific File by UUID
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Fetch a specific file using its unique identifier (UUID). The `file.info` attribute provides details about the file.
```python
file: File = uploadcare.file("740e1b8c-1ad8-4324-b7ec-112c79d8eac2")
print(file.info)
```
--------------------------------
### Get File CDN URL
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Retrieve the CDN URL for a given file. This is the base URL used for accessing and transforming files.
```python
>>> file_ = File('a771f854-c2cb-408a-8c36-71af77811f3b')
>>> file_.cdn_url
https://ucarecdn.com/a771f854-c2cb-408a-8c36-71af77811f3b/
```
--------------------------------
### Retrieve Document Conversion Information
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Get information about a document's format and possible conversion formats by providing its UUID to the document_convert_api.retrieve method.
```python
uuid = '740e1b8c-1ad8-4324-b7ec-112c79d8eac2'
uploadcare.document_convert_api.retrieve(uuid)
```
--------------------------------
### Get File Group by ID
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Retrieve a file group using its identifier, which typically includes the UUID and a count of files (e.g., `uuid~count`).
```python
file_group: FileGroup = uploadcare.file_group('0513dda0-582f-447d-846f-096e5df9e2bb~2')
print(file_group.info)
```
--------------------------------
### Initialization
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Initialize the Uploadcare client with your project's public and secret keys.
```APIDOC
## Initialization
You can use pyuploadcare in any Python project. You need to pass
your project keys to `Uploadcare` client:
```python
from pyuploadcare import Uploadcare
uploadcare = Uploadcare(
public_key='',
secret_key=''
)
```
```
--------------------------------
### Initialize Uploadcare Client
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Initialize the Uploadcare client with your project's public and secret keys. These keys are essential for authenticating your requests.
```python
from pyuploadcare import Uploadcare
uploadcare = Uploadcare(
public_key='',
secret_key=''
)
```
--------------------------------
### Initialize Uploadcare Client (v3.0+)
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/install.md
Initialize the Uploadcare client with your public and secret keys to access the API. This is the preferred method for configuration in version 3.0 and later.
```python
uploadcare = Uploadcare(
public_key='',
secret_key=''
)
```
--------------------------------
### Upload a File with pyuploadcare
Source: https://github.com/uploadcare/pyuploadcare/blob/main/README.md
Initialize the Uploadcare client with your API keys and upload a file from a local path. Ensure the file is opened in binary read mode.
```python
from pyuploadcare import Uploadcare
uploadcare = Uploadcare(public_key="demopublickey", secret_key="demoprivatekey")
with open("sample-file.jpeg", "rb") as file_object:
ucare_file = uploadcare.upload(file_object)
```
--------------------------------
### List File Groups
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Retrieve a list of all file groups in your project. You can specify a `limit` to control the number of groups returned.
```python
file_groups: List[FileGroup] = uploadcare.list_file_groups(limit=10)
for file_group in file_groups:
print(file_group.info)
```
--------------------------------
### Display Uploadcare CLI Help
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/quickstart.md
View the help message for the Uploadcare command-line interface tool.
```console
$ ucare -h
```
--------------------------------
### Configure pyuploadcare.dj in Django Settings
Source: https://github.com/uploadcare/pyuploadcare/blob/main/README.md
Add `pyuploadcare.dj` to your `INSTALLED_APPS` and configure your Uploadcare API keys in the Django settings file.
```python
INSTALLED_APPS = (
# ...
"pyuploadcare.dj",
"gallery",
)
UPLOADCARE = {
"pub_key": "demopublickey",
"secret": "demoprivatekey",
}
```
--------------------------------
### Arbitrary File Metadata
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Demonstrates how to set, update, delete, and retrieve arbitrary file metadata.
```APIDOC
## Arbitrary File Metadata
You can store some additional information for a file ([metadata documentation](https://uploadcare.com/api-refs/rest-api/v0.7.0/#tag/File-metadata)). Access is organized in key-value manner.
Metadata may be initially set while uploading:
```python
custom_metadata = {
"specific_key_1": "some_value_1",
"specific_key_2": "constant_for_this_planet",
}
with open('file.txt', 'rb') as file_object:
ucare_file = uploadcare.upload(file_object, metadata=custom_metadata)
```
While uploading multiple files at once you can set common metadata that will be applied for every file in collection:
```python
file1 = open('file1.txt', 'rb')
file2 = open('file2.txt', 'rb')
ucare_files = uploadcare.upload_files(
[file1, file2],
common_metadata=custom_metadata,
)
# don't forget to close the files, of course
```
Value may be set by key:
```python
md_key, md_value = "new_key_for_filemeta", "obvious_value"
uploadcare.metadata_api.update_or_create_key(file_id, md_key, md_value)
```
Value may be deleted by key:
```python
uploadcare.metadata_api.delete_key(file_id, mkey=md_key)
```
Value may be retrieved by key:
```python
meta_value = uploadcare.metadata_api.get_key(file_id, mkey=md_key)
```
Or the whole metadata may be got at once:
```python
file_metadata = uploadcare.metadata_api.get_all_metadata(file_id)
```
But you should better use a special attribute of File.info:
```python
file_metadata = file.info["metadata"]
```
```
--------------------------------
### Upload File from URL with Options
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Use `upload_from_url` to upload files from a URL with additional options like storing, setting filename, and managing duplicates.
```python
file_from_url: FileFromUrl = uploadcare.upload_from_url(
"https://github.githubassets.com/images/modules/logos_page/Octocat.png",
store=True,
filename="octocat.png",
check_duplicates=True,
save_duplicates=True,
)
```
--------------------------------
### List Webhooks
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Retrieves a list of all configured webhooks.
```APIDOC
## List Webhooks
### Description
Retrieves a list of all configured webhooks.
### Method
`uploadcare.list_webhooks`
### Parameters
- **limit** (integer, optional) - Optional - The maximum number of webhooks to return.
### Request Example
```python
webhooks = list(uploadcare.list_webhooks(limit=10))
```
### Response
- **webhooks** (List[Webhook object]) - A list of webhook objects.
### Response Example
```json
[
{
"id": "webhook_id_123",
"target_url": "https://path/to/webhook",
"is_active": true
}
]
```
```
--------------------------------
### Create Webhook
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Creates a new webhook to receive notifications for events.
```APIDOC
## Create Webhook
### Description
Creates a new webhook to receive notifications for events.
### Method
`uploadcare.create_webhook`
### Parameters
- **target_url** (string) - Required - The URL where webhook notifications will be sent.
- **signing_secret** (string, optional) - Optional - A secret key used for signing webhook requests.
### Request Example
```python
webhook = uploadcare.create_webhook(
target_url="https://path/to/webhook",
signing_secret="7kMVZivndx0ErgvhRKAr"
)
```
### Response
- **webhook** (Webhook object) - The created webhook object.
### Response Example
```json
{
"id": "webhook_id_123",
"target_url": "https://path/to/webhook",
"is_active": true,
"signing_secret": "7kMVZivndx0ErgvhRKAr"
}
```
```
--------------------------------
### Retrieve File Metadata by Key
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Fetch the value of a specific metadata entry for a file using its ID and the metadata key.
```python
meta_value = uploadcare.metadata_api.get_key(file_id, mkey=md_key)
```
--------------------------------
### Apply Image Effects via Builder
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Apply image effects using the ImageTransformation builder for a more programmatic approach. This allows for chaining multiple transformations.
```python
>>> file_.set_effects(ImageTransformation().grayscale().flip())
>>> file_.cdn_url
https://ucarecdn.com/a771f854-c2cb-408a-8c36-71af77811f3b/-/grayscale/-/flip/
```
--------------------------------
### Upload File from URL Synchronously
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Use `upload_from_url_sync` for a synchronous upload from a URL. This method is simpler if you don't need advanced options.
```python
ucare_file: File = uploadcare.upload_from_url_sync(
"https://github.githubassets.com/images/modules/logos_page/Octocat.png",
)
```
--------------------------------
### Execute Addon Operations
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Perform operations provided by addons by selecting a file and setting execution parameters. Some addons, like AWS Rekognition, may not require specific parameters.
```python
from pyuploadcare.api.addon_entities import AddonRemoveBGExecutionParams
remove_bg_params = AddonRemoveBGExecutionParams(
crop=True,
crop_margin="20px",
scale="15%"
)
from pyuploadcare.api.addon_entities import AddonClamAVExecutionParams
clamav_params = AddonClamAVExecutionParams(purge_infected=True)
```
```python
target_file = uploadcare.file("59fccca5-3af7-462f-905b-ed7de83b9762")
# params - from previous step
remove_bg_result = uploadcare.addons_api.execute(
target_file.uuid,
AddonLabels.REMOVE_BG,
remove_bg_params,
)
aws_recognition_result = uploadcare.addons_api.execute(
target_file.uuid,
AddonLabels.AWS_LABEL_RECOGNITION,
)
aws_moderation_result = uploadcare.addons_api.execute(
target_file.uuid,
AddonLabels.AWS_MODERATION_LABELS,
)
clamav_result = uploadcare.addons_api.execute(
target_file.uuid,
AddonLabels.CLAM_AV,
clamav_params,
)
```
--------------------------------
### Video Conversion
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Shows how to convert video files to different formats, adjust quality, dimensions, and extract fragments.
```APIDOC
## 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:
```python
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.convert(transformation)
```
or you can use API directly to convert single or multiple files:
```python
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)
```
```
--------------------------------
### Execute Addon
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Executes a specified addon for a given file with optional parameters and retrieves the task request ID.
```APIDOC
## Execute Addon
### Description
Executes a specified addon for a given file with optional parameters and retrieves the task request ID.
### Method
`uploadcare.addons_api.execute`
### Parameters
- **file_uuid** (string) - Required - The UUID of the file to process.
- **addon_name** (AddonLabels enum) - Required - The name of the addon to execute.
- **params** (object, optional) - Optional - Parameters specific to the addon.
### Request Example
```python
from pyuploadcare.api.addon_entities import AddonRemoveBGExecutionParams
remove_bg_params = AddonRemoveBGExecutionParams(
crop=True,
crop_margin="20px",
scale="15%"
)
target_file_uuid = "59fccca5-3af7-462f-905b-ed7de83b9762"
addon_result = uploadcare.addons_api.execute(
target_file_uuid,
AddonLabels.REMOVE_BG,
remove_bg_params
)
```
### Response
- **request_id** (string) - The ID of the asynchronous task.
### Response Example
```json
{
"request_id": "some_task_request_id"
}
```
```
--------------------------------
### Generate Secure URL with Transformations
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Create a secure URL for a file that includes transformations, such as resizing. The transformations are appended to the file UUID in the URL.
```python
secure_url = uploadcare.generate_secure_url(
'52da3bfc-7cd8-4861-8b05-126fef7a6994/-/resize/640x/other/transformations/'
)
```
--------------------------------
### Upload File with Custom Metadata
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Set arbitrary key-value metadata for a file during the upload process. Ensure the file object is opened in binary read mode.
```python
custom_metadata = {
"specific_key_1": "some_value_1",
"specific_key_2": "constant_for_this_planet",
}
with open('file.txt', 'rb') as file_object:
ucare_file: File = uploadcare.upload(file_object, metadata=custom_metadata)
```
--------------------------------
### Convert Video Files Directly via API
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Initiate video conversion for one or more files directly through the video_convert_api, specifying transformations and paths.
```python
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)
```
--------------------------------
### Uploading Files
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Methods for uploading single or multiple files, from local file objects or URLs, with options for duplicate checking and storage.
```APIDOC
## 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:
```python
with open('file.txt', 'rb') as file_object:
ucare_file: File = uploadcare.upload(file_object)
```
Upload file from url:
```python
ucare_file: File = uploadcare.upload("https://github.githubassets.com/images/modules/logos_page/Octocat.png")
```
Use `upload_from_url` or `upload_from_url_sync` to access additional parameters, such as `check_duplicates` and `save_duplicates`, when uploading from url:
```python
file_from_url: FileFromUrl = uploadcare.upload_from_url(
"https://github.githubassets.com/images/modules/logos_page/Octocat.png",
store=True,
filename="octocat.png",
check_duplicates=True,
save_duplicates=True,
)
ucare_file: File = uploadcare.upload_from_url_sync(
"https://github.githubassets.com/images/modules/logos_page/Octocat.png",
)
```
Upload multiple files. Direct upload method is used:
```python
file1 = open('file1.txt', 'rb')
file2 = open('file2.txt', 'rb')
ucare_files: List[File] = uploadcare.upload_files([file1, file2])
```
Send single file via multipart upload:
```python
with open('file.txt', 'rb') 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:
```python
>>> 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
```
```
--------------------------------
### Access Uploadcare Resources (v3.0+)
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/install.md
Use client methods to access File, FileGroup, FileList, and GroupList resources. Direct initialization of these classes is no longer supported.
```python
file: File = uploadcare.file('a771f854-c2cb-408a-8c36-71af77811f3b')
file_group: FileGroup = uploadcare.file_group('0513dda0-582f-447d-846f-096e5df9e2bb~2')
file_groups: GroupList = uploadcare.list_file_groups()
files: FileList = uploadcare.list_files(stored=True)
```
--------------------------------
### Enable Legacy Widget in Django (v5.0+)
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/install.md
Configure Django settings to use the old jQuery-based widget instead of the new file uploader introduced in version 5.0.
```python
UPLOADCARE = {
...,
"use_legacy_widget": True,
}
```
--------------------------------
### Create File Group
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Group multiple files together into a single entity. This requires `File` objects as input.
```python
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])
```
--------------------------------
### List Stored Files
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Retrieve a list of stored files. You can filter by `stored` status and set a `limit` for the number of results.
```python
files: FileList = uploadcare.list_files(stored=True, limit=10)
for file in files:
print(file.info)
```
--------------------------------
### Apply Image Effects via String
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Set default image effects by providing a string of transformations. This method is useful for simple, predefined effects.
```python
>>> file_.set_effects('effect/flip/-/effect/mirror/')
>>> file_.cdn_url
https://ucarecdn.com/a771f854-c2cb-408a-8c36-71af77811f3b/-/effect/flip/-/effect/mirror/
```
--------------------------------
### Convert Video File with Transformations
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Apply various transformations to a video file, such as format, size, quality, and cutting, using the VideoTransformation object.
```python
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)
```
--------------------------------
### Upload Multiple Files with Common Metadata
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Upload a collection of files while applying the same metadata to all of them. Remember to close the file objects after uploading.
```python
file1 = open('file1.txt', 'rb')
file2 = open('file2.txt', 'rb')
ucare_files: List[File] = uploadcare.upload_files(
[file1, file2],
common_metadata=custom_metadata,
)
# don't forget to close the files, of course
```
--------------------------------
### Generate Secure URL with Wildcard
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Generate a secure URL for a file where the signature is valid for all its transformations by setting the wildcard option to True.
```python
secure_url = uploadcare.generate_secure_url(
'52da3bfc-7cd8-4861-8b05-126fef7a6994',
wildcard=True
)
```
--------------------------------
### Apply Content-Aware Crop Transformation
Source: https://github.com/uploadcare/pyuploadcare/blob/main/README.md
Apply a content-aware ('smart') crop transformation to an image. This can be done using a string-based effect or the `ImageTransformation` object.
```python
from pyuploadcare.transformations.image import ImageTransformation, ScaleCropMode
# These two function calls are equivalent
ucare_file.set_effects("scale_crop/512x512/smart/")
ucare_file.set_effects(ImageTransformation().scale_crop(512, 512, mode=ScaleCropMode.smart))
print(ucare_file.cdn_url)
```
--------------------------------
### Update or Create File Metadata by Key
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Modify or add a specific metadata entry for a file using its unique identifier and a key-value pair.
```python
md_key, md_value = "new_key_for_filemeta", "obvious_value"
uploadcare.metadata_api.update_or_create_key(file_id, md_key, md_value)
```
--------------------------------
### Generate Secure URL with Akamai URL Token
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Generate a secure URL for a file using Akamai's CDN with a URL token. This method uses a different builder class and is suitable when providing the full file URL.
```python
from pyuploadcare import Uploadcare
from pyuploadcare.secure_url import AkamaiSecureUrlBuilderWithUrlToken
secure_url_bulder = AkamaiSecureUrlBuilderWithUrlToken(
"",
""
)
uploadcare = Uploadcare(
public_key='',
secret_key='',
secure_url_builder=secure_url_bulder,
)
secure_url = uploadcare.generate_secure_url(
'https://cdn.yourdomain.com/52da3bfc-7cd8-4861-8b05-126fef7a6994/'
)
```
--------------------------------
### Upload File with Progress Callback
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Attach a callback function to track the upload progress. The callback receives `UploadProgress` info with `done` and `total` bytes.
```python
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
```
--------------------------------
### Passing Widget Options via Django Settings
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/django-widget.md
Use the `widget_options` setting to pass arbitrary options to the Uploadcare file uploader, such as source list and camera mirror settings.
```python
UPLOADCARE = {
# ...
"widget": {
"options": {
"source-list": "local,url,camera",
"camera-mirror": True,
},
},
}
```
--------------------------------
### Construct CDN URL with Effects in Django Template
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/quickstart.md
Dynamically build CDN URLs for images in Django templates, applying transformations like resize and effects.
```django
{% for photo in photos %}
{{ photo.title }}
{{ photo.photo.cdn_url }}-/resize/400x300/-/effect/flip/-/effect/grayscale/
{% endfor %}
```
--------------------------------
### Convert Document Files Directly via API
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Convert document files to a specified format using the document_convert_api. This method allows batch conversion and returns conversion information.
```python
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)
```
--------------------------------
### List Webhooks
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Retrieve a list of existing webhooks, with an option to limit the number of results returned.
```python
webhooks: List[Webhook] = list(uploadcare.list_webhooks(limit=10))
```
--------------------------------
### Add pyuploadcare.dj to Django INSTALLED_APPS
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/quickstart.md
Include 'pyuploadcare.dj' in your Django project's INSTALLED_APPS to enable Uploadcare integration.
```python
INSTALLED_APPS = (
# ...
'pyuploadcare.dj',
'gallery',
)
```
--------------------------------
### Manage Files and File Groups
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Operations for listing, retrieving, storing, deleting files, and managing file groups.
```APIDOC
## Manage files and file groups
Get a list of files:
```python
files: FileList = uploadcare.list_files(stored=True, limit=10)
for file in files:
print(file.info)
```
Get an existing file:
```python
file: File = uploadcare.file("740e1b8c-1ad8-4324-b7ec-112c79d8eac2")
print(file.info)
```
Store a single file:
```python
file: File = uploadcare.file("740e1b8c-1ad8-4324-b7ec-112c79d8eac2")
file.store()
```
Store multiple files:
```python
files = [
'6c5e9526-b0fe-4739-8975-72e8d5ee6342',
'a771f854-c2cb-408a-8c36-71af77811f3b'
]
uploadcare.store_files(files)
```
Delete a single file:
```python
file: File = uploadcare.file("740e1b8c-1ad8-4324-b7ec-112c79d8eac2")
file.delete()
```
Delete multiple files:
```python
files = [
'6c5e9526-b0fe-4739-8975-72e8d5ee6342',
'a771f854-c2cb-408a-8c36-71af77811f3b'
]
uploadcare.delete_files(files)
```
Create a file group:
```python
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])
```
Get a file group:
```python
file_group: FileGroup = uploadcare.file_group('0513dda0-582f-447d-846f-096e5df9e2bb~2')
print(file_group.info)
```
Stores all group’s files:
```python
file_group: FileGroup = uploadcare.file_group('0513dda0-582f-447d-846f-096e5df9e2bb~2')
file_group.store()
```
List file groups:
```python
file_groups: List[FileGroup] = uploadcare.list_file_groups(limit=10)
for file_group in file_groups:
print(file_group.info)
```
Delete file groups:
```python
file_group: FileGroup = uploadcare.file_group('0513dda0-582f-447d-846f-096e5df9e2bb~2')
file_group.delete()
```
To delete a file group and all the files it contains:
```python
file_group: FileGroup = uploadcare.file_group('0513dda0-582f-447d-846f-096e5df9e2bb~2')
file_group.delete(delete_files=True)
```
Get project info:
```python
project_info: ProjectInfo = uploadcare.get_project_info()
```
```
--------------------------------
### Create Image of a Specific Document Page
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Generate an image (e.g., PNG) of a particular page from a document file. Specify the desired page number in the transformation.
```python
file = uploadcare.file('5dddafa0-a742-4a51-ac40-ae491201ff97')
transformation = DocumentTransformation().format(DocumentFormat.png).page(1)
converted_file: File = file.convert(transformation)
```
--------------------------------
### Convert Document to PDF
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Convert a document file to PDF format using the DocumentTransformation object. The converted file is returned as a File object.
```python
file = uploadcare.file('0e1cac48-1296-417f-9e7f-9bf13e330dcf')
transformation = DocumentTransformation().format(DocumentFormat.pdf)
converted_file: File = file.convert(transformation)
```
--------------------------------
### Legacy Widget Specific Settings
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/django-widget.md
Configure settings specific to the legacy Uploadcare widget, such as version, build, and custom JS URL.
```python
UPLOADCARE = {
# ...
"use_legacy_widget": True,
"legacy_widget": {
"version": "3.x", # ~= 3.0 (latest)
"build": "min", # without jQuery
"override_js_url": "http://path.to/your/uploadcare.js",
},
}
```
--------------------------------
### Minimal Django Settings for Uploadcare
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/django-widget.md
Configure your Django project with the minimal required Uploadcare settings, including your public and secret keys.
```python
UPLOADCARE = {
"pub_key": "",
"secret": "",
}
```
--------------------------------
### Enabling Signed Uploads in Django
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/django-widget.md
Enable the `signed_uploads` setting in your Django project if your Uploadcare project uses signed uploads to prevent widget upload failures.
```python
UPLOADCARE = {
# ...,
'signed_uploads': True,
}
```
--------------------------------
### Use LegacyFileWidget for jQuery-based Widget
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/django-widget.md
Switch to the jQuery-based widget on a field-by-field basis using LegacyFileWidget without enabling it globally.
```python
from django import forms
from pyuploadcare.dj.forms import LegacyFileWidget, ImageField
class CandidateForm(forms.Form):
photo = ImageField(widget=LegacyFileWidget)
```
--------------------------------
### Access File Metadata via File Info
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Retrieve all metadata for a file directly from the 'metadata' attribute within the file's info object.
```python
file_metadata = file.info["metadata"]
```
--------------------------------
### Define ImageField with Manual Crop
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/django-widget.md
Use ImageField for uploads that must be images. Set `manual_crop` to enable a cropping tool, with an empty string allowing any crop, or specific dimensions/ratios.
```python
from django.db import models
from pyuploadcare.dj.models import ImageField
class Candidate(models.Model):
photo = ImageField(blank=True, manual_crop="")
```
--------------------------------
### Store Single File
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Mark a single file as stored. This is useful for files that were initially uploaded without being stored.
```python
file: File = uploadcare.file("740e1b8c-1ad8-4324-b7ec-112c79d8eac2")
file.store()
```
--------------------------------
### Delete Multiple Files
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Delete multiple files at once by providing a list of their UUIDs. This is more efficient than deleting them individually.
```python
files = [
'6c5e9526-b0fe-4739-8975-72e8d5ee6342',
'a771f854-c2cb-408a-8c36-71af77811f3b'
]
uploadcare.delete_files(files)
```
--------------------------------
### Create Webhook
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Create a new webhook to receive notifications from Uploadcare. You can optionally provide a signing secret for webhook security.
```python
webhook: Webhook = uploadcare.create_webhook("https://path/to/webhook")
```
```python
webhook = uploadcare.create_webhook(
target_url="https://path/to/webhook",
signing_secret="7kMVZivndx0ErgvhRKAr",
)
```
--------------------------------
### Store Multiple Files
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Store multiple files efficiently by providing a list of their UUIDs. This operation is performed in a single API call.
```python
files = [
'6c5e9526-b0fe-4739-8975-72e8d5ee6342',
'a771f854-c2cb-408a-8c36-71af77811f3b'
]
uploadcare.store_files(files)
```
--------------------------------
### Upload Multiple Files
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Upload multiple files simultaneously using a list of file objects. This method utilizes direct upload.
```python
file1 = open('file1.txt', 'rb')
file2 = open('file2.txt', 'rb')
ucare_files: List[File] = uploadcare.upload_files([file1, file2])
```
--------------------------------
### Advanced Widget Options for ImageField
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/django-widget.md
Pass advanced widget options to FileWidget's attrs argument to customize the upload experience, such as enabling local, URL, and camera sources, and camera mirroring.
```python
from django import forms
from pyuploadcare.dj.forms import FileWidget, ImageField
# Optional: provide advanced widget options https://uploadcare.com/docs/file-uploader/options/
class CandidateForm(forms.Form):
photo = ImageField(widget=FileWidget(attrs={
"source-list": "local,url,camera",
"camera-mirror": True,
}))
```
--------------------------------
### Retrieve Addon Data
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
If an addon execution produces new data for a file, such as AWS recognition results, this data will be available in the appdata complex attribute of the File.info object. Ensure to include appdata when updating file information.
```python
file.update_info(include_appdata=True)
print(file.info["appdata"]["aws_rekognition_detect_labels"])
```
--------------------------------
### Configure Uploadcare API Keys in Django Settings
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/quickstart.md
Add your public and secret API keys to the Django settings file under the UPLOADCARE dictionary.
```python
UPLOADCARE = {
'pub_key': 'demopublickey',
'secret': 'demoprivatekey',
}
```
--------------------------------
### Generate Secure URL
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Generates a secure URL for a file, optionally with transformations, using a configured secure URL builder.
```APIDOC
## Generate Secure URL
### Description
Generates a secure URL for a file, optionally with transformations, using a configured secure URL builder.
### Method
`uploadcare.generate_secure_url`
### Parameters
- **file_uuid_or_url** (string) - Required - The UUID or URL of the file.
- **transformations** (string, optional) - Optional - Transformations to apply to the file (e.g., `/-/resize/640x/`).
- **wildcard** (boolean, optional) - Optional - If true, the signature will be valid for all transformations.
### Request Example
```python
# Using AkamaiSecureUrlBuilderWithAclToken
from pyuploadcare import Uploadcare
from pyuploadcare.secure_url import AkamaiSecureUrlBuilderWithAclToken
secure_url_builder = AkamaiSecureUrlBuilderWithAclToken(
"",
""
)
uploadcare = Uploadcare(
public_key='',
secret_key='',
secure_url_builder=secure_url_builder,
)
secure_url = uploadcare.generate_secure_url('52da3bfc-7cd8-4861-8b05-126fef7a6994')
# With transformations
secure_url_with_transformations = uploadcare.generate_secure_url(
'52da3bfc-7cd8-4861-8b05-126fef7a6994/-/resize/640x/other/transformations/'
)
# With wildcard for all transformations
secure_url_wildcard = uploadcare.generate_secure_url(
'52da3bfc-7cd8-4861-8b05-126fef7a6994',
wildcard=True
)
# Using AkamaiSecureUrlBuilderWithUrlToken
from pyuploadcare.secure_url import AkamaiSecureUrlBuilderWithUrlToken
secure_url_builder_url = AkamaiSecureUrlBuilderWithUrlToken(
"",
""
)
uploadcare_url = Uploadcare(
public_key='',
secret_key='',
secure_url_builder=secure_url_builder_url,
)
secure_url_from_url = uploadcare_url.generate_secure_url(
'https://cdn.yourdomain.com/52da3bfc-7cd8-4861-8b05-126fef7a6994/'
)
```
### Response
- **secure_url** (string) - The generated secure URL for the file.
```
--------------------------------
### Upload Single File from File Object
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Upload a single file from a file object. The library automatically selects between direct or multipart upload based on file size.
```python
with open('file.txt', 'rb') as file_object:
ucare_file: File = uploadcare.upload(file_object)
```
--------------------------------
### Full Default Django Uploadcare Configuration
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/django-widget.md
View the complete default configuration for Uploadcare in Django, including all optional settings.
```python
UPLOADCARE = {
"pub_key": "",
"secret": "",
"cdn_base": None,
"upload_base_url": None,
"signed_uploads": False,
"use_legacy_widget": False,
"use_hosted_assets": True,
"widget": {
"version": "1",
"variant": "regular",
"build": "min",
"options": {},
"override_js_url": None,
"override_css_url": {
"regular": None,
"inline": None,
"minimal": None,
},
},
"legacy_widget": {
"version": "3.x",
"build": "full.min",
"override_js_url": None,
},
}
```
--------------------------------
### Convert Multipage Document to Group of Images
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Convert all pages of a multipage document into a group of image files (e.g., JPG). The converted pages are saved as a FileGroup.
```python
file = uploadcare.file('0e1cac48-1296-417f-9e7f-9bf13e330dcf')
transformation = DocumentTransformation().format(DocumentFormat.jpg)
file.convert(transformation, save_in_group=True)
converted_group: FileGroup = file.get_converted_document_group(DocumentFormat.jpg)
```
--------------------------------
### Generate Secure URL with Akamai ACL Token
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Generate a secure URL for a file using Akamai's CDN with an ACL token. This requires configuring the Uploadcare client with a specific secure URL builder and your CDN credentials.
```python
from pyuploadcare import Uploadcare
from pyuploadcare.secure_url import AkamaiSecureUrlBuilderWithAclToken
secure_url_bulder = AkamaiSecureUrlBuilderWithAclToken(
"",
""
)
uploadcare = Uploadcare(
public_key='',
secret_key='',
secure_url_builder=secure_url_bulder,
)
secure_url = uploadcare.generate_secure_url('52da3bfc-7cd8-4861-8b05-126fef7a6994')
```
--------------------------------
### Custom Upload Handler URL
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/django-widget.md
Configure a custom URL for the Uploadcare widget's upload handler if needed.
```python
UPLOADCARE = {
# ...
"upload_base_url": "http://path.to/your/upload/handler",
}
```
--------------------------------
### Generate Secure URL Token
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Obtain just the secure URL token for a given file UUID, which can be used separately or with transformations.
```python
token = uploadcare.get_secure_url_token('52da3bfc-7cd8-4861-8b05-126fef7a6994')
```
--------------------------------
### Document Conversion
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Explains how to convert documents to various formats, create images of specific pages, or group converted pages.
```APIDOC
## 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:
```python
file = uploadcare.file('0e1cac48-1296-417f-9e7f-9bf13e330dcf')
transformation = DocumentTransformation().format(DocumentFormat.pdf)
converted_file = file.convert(transformation)
```
or create an image of a particular page (if using image format):
```python
file = uploadcare.file('5dddafa0-a742-4a51-ac40-ae491201ff97')
transformation = DocumentTransformation().format(DocumentFormat.png).page(1)
converted_file = file.convert(transformation)
```
or create a file group of converted pages of a multipage document:
```python
file = uploadcare.file('0e1cac48-1296-417f-9e7f-9bf13e330dcf')
transformation = DocumentTransformation().format(DocumentFormat.jpg)
file.convert(transformation, save_in_group=True)
converted_group = file.get_converted_document_group(DocumentFormat.jpg)
```
or you can use API directly to convert single or multiple files:
```python
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)
```
Determine the document format and possible conversion formats:
```python
uuid = '740e1b8c-1ad8-4324-b7ec-112c79d8eac2'
uploadcare.document_convert_api.retrieve(uuid)
```
```
--------------------------------
### Include Form Media in Django Template
Source: https://github.com/uploadcare/pyuploadcare/blob/main/README.md
Ensure that the necessary scripts for Uploadcare widgets are loaded in your Django templates by including `{{ form.media }}` within the `` tag.
```htmldjango
{{ form.media }}
```
--------------------------------
### Storing Uploadcare Files Manually
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/django-widget.md
Demonstrates how to manually store an Uploadcare file object when it's not automatically handled by Django's form validation or model cleaning.
```python
photo.photo_2x3 = File("a771f854-c2cb-408a-8c36-71af77811f3b")
photo.save()
photo.photo_2x3.store()
```
--------------------------------
### Store All Files in a Group
Source: https://github.com/uploadcare/pyuploadcare/blob/main/docs/core_api.md
Store all individual files that belong to a specific file group. This operation applies to each file within the group.
```python
file_group: FileGroup = uploadcare.file_group('0513dda0-582f-447d-846f-096e5df9e2bb~2')
file_group.store()
```