Utilities

Utility functions related to the djstripe app.

Attributes

djstripe.utils.CURRENCY_SIGILS = {'CAD': '$', 'EUR': '€', 'GBP': '£', 'USD': '$'} module-attribute

Classes

djstripe.utils.QuerySetMock

Bases: QuerySet

A mocked QuerySet class that does not handle updates. Used by UpcomingInvoice.invoiceitems.

Source code in djstripe/utils.py
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
class QuerySetMock(QuerySet):
    """
    A mocked QuerySet class that does not handle updates.
    Used by UpcomingInvoice.invoiceitems.
    """

    @classmethod
    def from_iterable(cls, model, iterable):
        instance = cls(model)
        instance._result_cache = list(iterable)
        instance._prefetch_done = True
        return instance

    def _clone(self):
        return self.__class__.from_iterable(self.model, self._result_cache)

    def update(self):
        return 0

    def delete(self):
        return 0

Functions

djstripe.utils.QuerySetMock.delete()
Source code in djstripe/utils.py
82
83
def delete(self):
    return 0
djstripe.utils.QuerySetMock.from_iterable(model, iterable) classmethod
Source code in djstripe/utils.py
69
70
71
72
73
74
@classmethod
def from_iterable(cls, model, iterable):
    instance = cls(model)
    instance._result_cache = list(iterable)
    instance._prefetch_done = True
    return instance
djstripe.utils.QuerySetMock.update()
Source code in djstripe/utils.py
79
80
def update(self):
    return 0

Functions

djstripe.utils.clear_expired_idempotency_keys()

Source code in djstripe/utils.py
31
32
33
34
35
def clear_expired_idempotency_keys():
    from .models import IdempotencyKey

    threshold = timezone.now() - datetime.timedelta(hours=24)
    IdempotencyKey.objects.filter(created__lt=threshold).delete()

djstripe.utils.convert_tstamp(response)

Convert a Stripe API timestamp response (unix epoch) to a native datetime.

Source code in djstripe/utils.py
38
39
40
41
42
43
44
45
46
47
48
49
def convert_tstamp(response) -> Optional[datetime.datetime]:
    """
    Convert a Stripe API timestamp response (unix epoch) to a native datetime.
    """
    if response is None:
        # Allow passing None to convert_tstamp()
        return response

    # Overrides the set timezone to UTC - I think...
    tz = timezone.utc if settings.USE_TZ else None

    return datetime.datetime.fromtimestamp(response, tz)

djstripe.utils.get_friendly_currency_amount(amount, currency)

Source code in djstripe/utils.py
56
57
58
59
60
def get_friendly_currency_amount(amount, currency: str) -> str:
    currency = currency.upper()
    sigil = CURRENCY_SIGILS.get(currency, "")
    amount_two_decimals = f"{amount:.2f}"
    return f"{sigil}{intcomma(amount_two_decimals)} {currency}"

djstripe.utils.get_id_from_stripe_data(data)

Extract stripe id from stripe field data

Source code in djstripe/utils.py
86
87
88
89
90
91
92
93
94
95
96
97
98
def get_id_from_stripe_data(data):
    """
    Extract stripe id from stripe field data
    """

    if isinstance(data, str):
        # data like "sub_6lsC8pt7IcFpjA"
        return data
    elif data:
        # data like {"id": sub_6lsC8pt7IcFpjA", ...}
        return data.get("id")
    else:
        return None

djstripe.utils.get_model(model_name)

Source code in djstripe/utils.py
101
102
103
104
105
def get_model(model_name):
    app_label = "djstripe"
    app_config = apps.get_app_config(app_label)
    model = app_config.get_model(model_name)
    return model

djstripe.utils.get_queryset(pks, model_name)

Source code in djstripe/utils.py
108
109
110
def get_queryset(pks, model_name):
    model = get_model(model_name)
    return model.objects.filter(pk__in=pks)

djstripe.utils.get_supported_currency_choices(api_key)

Pull a stripe account's supported currencies and returns a choices tuple of those supported currencies.

:param api_key: The api key associated with the account from which to pull data. :type api_key: str

Source code in djstripe/utils.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
def get_supported_currency_choices(api_key):
    """
    Pull a stripe account's supported currencies and returns a choices tuple of those
    supported currencies.

    :param api_key: The api key associated with the account from which to pull data.
    :type api_key: str
    """
    account = stripe.Account.retrieve(api_key=api_key)
    supported_payment_currencies = stripe.CountrySpec.retrieve(
        account["country"], api_key=api_key
    )["supported_payment_currencies"]

    return [(currency, currency.upper()) for currency in supported_payment_currencies]