Skip to main content

Tools For S3 Used By Saritasa

Project description

saritasa-s3-tools

GitHub Workflow Status (with event) PyPI PyPI - Status PyPI - Python Version PyPI - Django Version PyPI - License PyPI - Downloads Ruff

Extension for boto3 to ease work with s3

Table of contents

Installation

pip install saritasa-s3-tools

or if you are using poetry

poetry add saritasa-s3-tools

Features

  • S3Client and AsyncS3Client for integrations with s3 buckets. This clients are extension to boto3 clients with proper typing, support for async and method to generate signed urls for file upload.
  • S3FileTypeConfig for defining configuration parameters for direct upload to s3. Check out more
  • S3Key for generating unique keys for s3 upload, used for S3FileTypeConfig
  • S3FileField and S3ImageFileField - factory-boy fields for generating files and saving it in s3
  • pytest plugin with fixtures for boto3, S3Client and AsyncS3Client and etc
  • Django plugin for setting up models and api

Django

saritasa-s3-tools comes with django plugin which helps with models config and api(Django Rest Framework and drf_spectacular). You can try it out in example folder.

Setup model

First you need to add file/image fields to you model, like below

import saritasa_s3_tools.django

from django.db import models

class ModelWithFiles(models.Model):
    """Test model with different files configs."""

    file = saritasa_s3_tools.django.S3FileField(
        blank=True,
        null=True,
        # S3FileTypeConfig is needed so that we could understand where to save
        # file, who can save file, what files can be save and what are size
        # constraints
        s3_config=saritasa_s3_tools.S3FileTypeConfig(
            name="django-files",
            key=saritasa_s3_tools.keys.WithPrefixUUIDFolder("django-files"),
            allowed=("text/plain",),
            auth=lambda user: bool(user and user.is_authenticated),
            content_length_range=(1000, 20000000),
        ),
    )

    image = saritasa_s3_tools.django.S3ImageField(
        blank=True,
        null=True,
        s3_config=saritasa_s3_tools.S3FileTypeConfig(
            name="django-images",
            key=saritasa_s3_tools.keys.WithPrefixUUIDFolder("django-images"),
            allowed=("image/png",),
            content_length_range=(5000, 20000000),
        ),
    )

Setup serializers

Then add S3FieldsConfigMixin mixin to your serializer, like this

from rest_framework import serializers

import saritasa_s3_tools.django

from .. import models


class ModelWithFilesSerializer(
    saritasa_s3_tools.django.S3FieldsConfigMixin,
    serializers.ModelSerializer,
):
    """Serializer to show info model with files."""

    class Meta:
        model = models.ModelWithFiles
        fields = "__all__"

Setup view

Then just add S3GetParamsView view to your project urls like that.

from django.urls import path

path(
    "s3/",
    include("saritasa_s3_tools.django.urls"),
    name="saritasa-s3-tools",
),

Setup pytest

Just add this to core conftest.py file

import pytest


@pytest.fixture(scope="session", autouse=True)
def _adjust_s3_bucket(django_adjust_s3_bucket: None) -> None:
    """Set bucket to a test one."""

Setup settings

AWS_S3_SIGNATURE_VERSION = "s3v4"

By default we assume s3v4 version for signature. We recommend that you would set AWS_S3_SIGNATURE_VERSION to s3v4. If you need other versions, set it in AWS_S3_SIGNATURE_VERSION and update SARITASA_S3_TOOLS_UPLOAD_PARAMS (defaults are here) setting to reflect expected fields that would return.

Optional dependencies

  • [async] - Add this to enable async support
  • [factory] - Add this to enable factory-boy field S3FileField and S3ImageFileField from saritasa_s3_tools.factory
  • [testing] - Add this to enable testing helping functions from saritasa_s3_tools.testing.shortcuts
  • [django] - Add this to enable django support
  • [django-openapi] - Add this to enable drf-spectacular support

To install all optional dependencies add [all]

Direct upload example

import saritasa_s3_tools
import pathlib
import xml.etree.ElementTree

s3_client = saritasa_s3_tools.S3Client(
    boto3_client=boto3_client,
    default_bucket=s3_bucket,
)
s3_params = s3_client.generate_params(
    filename=pathlib.Path(__file__).name,
    config=saritasa_s3_tools.S3FileTypeConfig.configs["files"],
    content_type="application/x-python-code",
    extra_metadata={
        "test": "123",
    },
)
with (
    httpx.Client() as client,
    pathlib.Path(__file__).open("rb") as upload_file,
):
    upload_response = client.post(
        url=s3_params.url,
        data={
            key: value
            for key, value in s3_params.params.items()
            if value is not None
        },
        files={"file": upload_file.read()},
    )
parsed_response = xml.etree.ElementTree.fromstring(  # noqa: S314
    upload_response.content.decode(),
)
file_key = parsed_response[2].text
file_url = parsed_response[0].text

pytest plugin

saritasa-s3-tools comes with pytest plugin which can setup boto3 instances and create/clean up buckets for testing. Supports pytest-xdist.

Fixtures

  • access_key_getter, s3_endpoint_url_getter, s3_region - are used to configure boto3 session and clients/resources that are used in tests. You can override them or set values in ini file for pytest. Plugin will tell what you are missing.
  • aws_session - Returns boto3.Session
  • aws_config - Returns botocore.config.Config, override if you need customization, None by default.
  • boto3_resource - Returns s3 resource or in typing mypy_boto3_s3.S3ServiceResource
  • boto3_client- Returns s3 client or in typing mypy_boto3_s3.S3Client
  • s3_bucket_name - Name of bucket for testing, default: saritasa-s3-tools or s3_bucket_name from ini file.
  • s3_bucket_cleaner - Returns function which cleans all files from bucket
  • s3_bucket_factory - Returns manager which creates bucket, and when it's no longer needed deletes it
  • s3_bucket - Creates bucket via s3_bucket_factory and return it's name
  • s3_client - Returns saritasa_s3_tools.S3Client
  • async_s3_client - Returns saritasa_s3_tools.AsyncS3Client

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

saritasa_s3_tools-0.4.0.tar.gz (21.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

saritasa_s3_tools-0.4.0-py3-none-any.whl (23.5 kB view details)

Uploaded Python 3

File details

Details for the file saritasa_s3_tools-0.4.0.tar.gz.

File metadata

  • Download URL: saritasa_s3_tools-0.4.0.tar.gz
  • Upload date:
  • Size: 21.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.1 CPython/3.13.2 Linux/6.6.84-1-MANJARO

File hashes

Hashes for saritasa_s3_tools-0.4.0.tar.gz
Algorithm Hash digest
SHA256 80c08cb7293b6a16600200145e3f2eb967d7cc368ed395d4a0fb3a90ea2a20d3
MD5 e235c5b43857c23dcb57a14232713948
BLAKE2b-256 eb2b3053bb69b03f78fc7d2b287c62167b6c453fae01309c8c8a743fabf2fe5b

See more details on using hashes here.

File details

Details for the file saritasa_s3_tools-0.4.0-py3-none-any.whl.

File metadata

  • Download URL: saritasa_s3_tools-0.4.0-py3-none-any.whl
  • Upload date:
  • Size: 23.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.1 CPython/3.13.2 Linux/6.6.84-1-MANJARO

File hashes

Hashes for saritasa_s3_tools-0.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 6443444c27f27e790c2f0f6426eedfe00bd639e38089293b16ecf871adf67e3b
MD5 26704a6771d7d8ca1e99f426a96675b4
BLAKE2b-256 b98eaf6112b1ec201a3659ef3e453126f17c384a12ed4e29b0c5db7991cc62f5

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page