Models¶
Core models¶
There are two core models in Anchor:
Blobswhich take care of storing a pointer to each file uploaded plus some metadata, andAttachmentswhich act as a bridge between your own models andBlobs, allowing you to attach files to your own records.
These, together with the VariantRecord are the only models backed by a
database table. The rest of the classes within the anchor.models module only
contain business logic.
- class anchor.models.blob.blob.Blob(*args, **kwargs)¶
Stores metadata for files stored by Django Anchor.
- exception DoesNotExist¶
- exception MultipleObjectsReturned¶
- exception NotUpdated¶
- backend¶
The name of the storage backend as defined in
settings.STORAGESwhere the file is stored.This property is just the name of the backend. To get a storage instance with the backend’s configuration see
storage.
- byte_size¶
Size of the file in bytes, calculated automatically when the file is uploaded.
- calculate_checksum(file: File) str¶
Computes the MD5 hash of the given file and returns it as a (URL-safe) base64-encoded string.
- checksum¶
The MD5 checksum of the file.
- property custom_metadata¶
Arbitrary metadata you want to store for this blob.
- filename¶
The original filename of the file as it was uploaded.
- get_signed_id(purpose: str = None, expires_in: timedelta = None, expires_at: datetime = None)¶
Returns a signed ID of the blob.
Signed IDs can be shared with users securely because they can include an expiration.
- Parameters:
purpose (str, optional) – A string identifying the purpose of the signed ID. Used to restrict usage of the signed ID to specific contexts.
expires_in (timezone.timedelta, optional) – Time duration after which the signed ID will expire.
expires_at (timezone.datetime, optional) – Specific datetime at which the signed ID will expire.
- Returns:
A signed ID string that can be used to securely reference this blob.
- Return type:
str
- guess_mime_type(file: File)¶
Guesses the MIME type of the given file from its name.
If the file name is not available, returns the default MIME type.
- property is_image¶
Whether the file is an image.
- key¶
A pointer to the file that the storage backend can understand. For instance in file-system backends, this is a path to the file, relative to the
MEDIA_ROOT.
- metadata¶
Arbitrary metadata file, e.g. including the
widthandheightof an image.If you need to store custom metadata, refer to the
custom_metadataproperty.
- mime_type¶
A MIME type for the file derived from the extension.
MIME types are used to determine how files should be served:
image/*are served inline, while other types are served as attachments for security.
- open(mode='rb')¶
Opens the file from the storage backend.
This method might involve a download if the storage backend is not local. It can be used as a context manager.
- purge()¶
Deletes the file from the storage backend.
- property signed_id¶
A signed ID of the Blob, used to generate URLs.
- property storage: Storage¶
The Django storage backend where the file is persisted.
Instantiated by looking up the configuration in
settingsfor this object’sbackend.
- classmethod unsign_id(signed_id: str, purpose: str = None)¶
Un-signs a signed ID of a blob.
- Parameters:
signed_id (str) – The signed ID to un-sign.
purpose (str, optional) – The purpose with which the signed ID was created.
- Raises:
BadSignature – If the signature is invalid, has expired, or was signed with a different purpose.
- Returns:
The key of the blob.
- Return type:
str
- url(expires_in: timedelta = None, disposition: str = 'inline', filename: str = None)¶
Returns a URL to the file’s location in the storage backend.
Depending on the backend, this URL can be permanent (like in file-system-based backends). Instead of sharing this URL directly, refer to the
blob_urltemplate tag to generate a signed, expiring URL.By default, the blob’s own
filenameis forwarded to the storage backend so that browsers suggest a sensible name when displaying or saving the file. Pass an explicitfilenameto override that value at the call site.
- class anchor.models.attachment.Attachment(*args, **kwargs)¶
An attachment relates your own models to Blobs.
Most properties are proxies to the Blob.
- exception DoesNotExist¶
- exception MultipleObjectsReturned¶
- exception NotUpdated¶
- blob¶
A reference to the Blob which stores the file for this attachment.
- content_object¶
The actual object this attachment points to.
- content_type¶
Content Type (as in Django content types) of the object this attachment points to.
- property filename¶
The filename of the file stored in the storage backend.
- property is_image: bool¶
Whether the file is an image.
- name¶
The name of this attachment.
- object_id¶
ID of the object this attachment points to.
- order¶
The order of this attachment in the list of attachments.
- purge()¶
Deletes the file from the storage backend.
- representation(transformations: dict[str, Any])¶
Returns a representation of the file. See
the docs on representationsfor full details.
- property signed_id¶
Returns a signed ID for this attachment.
- url(**kwargs)¶
Returns a URL to the file’s location in the storage backend.
Fields¶
Model fields are how you allow your models to hold files.
- class anchor.models.fields.SingleAttachmentField(upload_to: str | Callable[[Model, Blob], str] = None, backend: str = None, **kwargs)¶
Enables a model to hold a single attachment.
When accessing this field, you’ll get an
Attachmentinstance. To set the file attachment, you can assign a plain file-like object, aBlobinstance or anAttachmentinstance.Example
A SingleAttachmentField allows attaching a single file to a model instance:
>>> from django.db import models >>> from anchor.models.fields import SingleAttachmentField >>> >>> class Movie(models.Model): ... title = models.CharField(max_length=100) ... cover = SingleAttachmentField( ... upload_to="movie-covers", ... help_text="A colorful image of the movie." ... ) ... >>> movie = Movie.objects.create(title="The Matrix") >>> movie.cover = uploaded_file # Attach a file >>> movie.cover.url() # Get URL to original file '/media/movie-covers/matrix-cover.jpg'
Representations¶
- exception anchor.models.blob.representations.NotRepresentableError¶
Raised when attempting to create a variant or preview which is not compatible with the original file.
- class anchor.models.blob.representations.RepresentationsMixin¶
Adds methods to the
Blobmodel to generate representations of files.Image files (those with a MIME type starting with
image/) can be varied by applying a series of transformations like resizing them or changing their format.Other kinds of files do not admit the same transformations as images, but can still be represented as an image, for instance, by generating a thumbnail of the first page of a PDF or a frame of a video.
Previews are not yet implemented, but the
representation()method is designed to wrap both and decide internally if it should callvariant()orpreview()depending on the kind of file.If you call
representation()on a file that is not representable (e.g. trying to resize a SVG file), aNotRepresentableErrorwill be raised.- property is_representable: bool¶
Checks whether the file can represented by an image or, if it is already an image, whether it can be transformed.
- representation(transformations: dict[str, Any])¶
Returns a
VariantorPreviewobject wrapping the result of applying the giventransformationsto this file.
- class anchor.models.variant_record.VariantRecord(id, created_at, blob, variation_digest)¶
- exception DoesNotExist¶
- exception MultipleObjectsReturned¶
- exception NotUpdated¶
- class anchor.models.variation.Variation(transformations: dict[str, Any])¶
Represents a (set of) transformations of an image file.
- classmethod decode(key: str) Self¶
Decodes a signed variation key and returns a Variation.
- default_to(default_transformations: dict[str, Any]) None¶
Updates the keys missing from this object’s
transformationswith the givendefault_transformations.
- property digest: str¶
A hash of the transformations dictionary in this variation.
This is a good way to check if two variations are the same, but keep in mind that order is important in transformations, so two Variations with the same transformations in different orders will have different digests.
- classmethod encode(transformations: dict[str, Any]) str¶
Encodes a transformations dictionary as a signed string.
- property key: str¶
Returns a variation key for this object.
Keys are signed to ensure they are not tampered with, but they are permanent so they should be shared with care.
- property mime_type: str¶
Returns the MIME type that the result of applying this variation to an image file will have.
It is determined from the
formattransformation: e.g. specifying'format': 'webp'will return'image/webp'.
- transform(file)¶
Applies the transformations to the given file and makes it available as a temporary file in a context manager.
- property transformer: BaseTransformer¶
Returns the transformer to be used to perform the transformations in this variation.
- classmethod wrap(value: str | dict[str, Any] | Self) Self¶
Returns a variation object, either by decoding a variation key or by wrapping a dictionary of transformations.
If the argument is already a variation object, it is returned as is.