Skip to content

Commit

Permalink
Black
Browse files Browse the repository at this point in the history
  • Loading branch information
Stranger6667 committed May 14, 2019
1 parent ce956d9 commit 0184f86
Show file tree
Hide file tree
Showing 50 changed files with 1,030 additions and 1,105 deletions.
4 changes: 2 additions & 2 deletions djmoney/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# -*- coding: utf-8 -*-

__version__ = '0.15.dev'
default_app_config = 'djmoney.apps.MoneyConfig'
__version__ = "0.15.dev"
default_app_config = "djmoney.apps.MoneyConfig"
15 changes: 9 additions & 6 deletions djmoney/_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,10 @@
from django.core.validators import DecimalValidator

class MoneyValidator(DecimalValidator):

def __call__(self, value):
return super(MoneyValidator, self).__call__(value.amount)


except ImportError:
MoneyValidator = None

Expand All @@ -46,14 +46,17 @@ def setup_managers(sender):
from .models.managers import money_manager

if VERSION >= (1, 11):
default_manager_name = sender._meta.default_manager_name or 'objects'
default_manager_name = sender._meta.default_manager_name or "objects"
for manager in filter(lambda m: m.name == default_manager_name, sender._meta.local_managers):
money_manager(manager)
else:
sender.copy_managers([
(_id, name, money_manager(manager))
for _id, name, manager in sender._meta.concrete_managers if name == 'objects'
])
sender.copy_managers(
[
(_id, name, money_manager(manager))
for _id, name, manager in sender._meta.concrete_managers
if name == "objects"
]
)


def get_success_style(style):
Expand Down
2 changes: 1 addition & 1 deletion djmoney/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,4 @@ def display_for_field(value, field, empty):
return original_display_for_field(value, field, empty)

for mod in MODULES_TO_PATCH:
setattr(mod, 'display_for_field', display_for_field)
setattr(mod, "display_for_field", display_for_field)
2 changes: 1 addition & 1 deletion djmoney/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@


class MoneyConfig(AppConfig):
name = 'djmoney'
name = "djmoney"

def ready(self):
try:
Expand Down
2 changes: 1 addition & 1 deletion djmoney/contrib/django_rest_framework/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class MoneyField(DecimalField):
"""

def __init__(self, *args, **kwargs):
self.default_currency = kwargs.pop('default_currency', None)
self.default_currency = kwargs.pop("default_currency", None)
super(MoneyField, self).__init__(*args, **kwargs)
# Rest Framework converts `min_value` / `max_value` to validators, that are not aware about `Money` class
# We need to adjust them
Expand Down
8 changes: 4 additions & 4 deletions djmoney/contrib/exchange/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@


class RateAdmin(admin.ModelAdmin):
list_display = ('currency', 'value', 'last_update', 'backend')
list_filter = ('currency', )
ordering = ('currency', )
readonly_fields = ('backend', )
list_display = ("currency", "value", "last_update", "backend")
list_filter = ("currency",)
ordering = ("currency",)
readonly_fields = ("backend",)

def last_update(self, instance):
return instance.backend.last_update
Expand Down
16 changes: 9 additions & 7 deletions djmoney/contrib/exchange/backends/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,22 +49,24 @@ def get_response(self, **params):

def parse_json(self, response):
if isinstance(response, bytes):
response = response.decode('utf-8')
response = response.decode("utf-8")
return json.loads(response, parse_float=Decimal)

@atomic
def update_rates(self, base_currency=settings.BASE_CURRENCY, **kwargs):
"""
Updates rates for the given backend.
"""
backend, _ = ExchangeBackend.objects.update_or_create(name=self.name, defaults={'base_currency': base_currency})
backend, _ = ExchangeBackend.objects.update_or_create(name=self.name, defaults={"base_currency": base_currency})
backend.clear_rates()
params = self.get_params()
params.update(base_currency=base_currency, **kwargs)
Rate.objects.bulk_create([
Rate(currency=currency, value=value, backend=backend)
for currency, value in self.get_rates(**params).items()
])
Rate.objects.bulk_create(
[
Rate(currency=currency, value=value, backend=backend)
for currency, value in self.get_rates(**params).items()
]
)


class SimpleExchangeBackend(BaseExchangeBackend):
Expand All @@ -75,4 +77,4 @@ class SimpleExchangeBackend(BaseExchangeBackend):

def get_rates(self, **params):
response = self.get_response(**params)
return self.parse_json(response)['rates']
return self.parse_json(response)["rates"]
6 changes: 3 additions & 3 deletions djmoney/contrib/exchange/backends/fixer.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@


class FixerBackend(SimpleExchangeBackend):
name = 'fixer.io'
name = "fixer.io"

def __init__(self, url=settings.FIXER_URL, access_key=settings.FIXER_ACCESS_KEY):
if access_key is None:
raise ImproperlyConfigured('settings.FIXER_ACCESS_KEY should be set to use FixerBackend')
raise ImproperlyConfigured("settings.FIXER_ACCESS_KEY should be set to use FixerBackend")
self.url = url
self.access_key = access_key

def get_params(self):
return {'access_key': self.access_key}
return {"access_key": self.access_key}
6 changes: 3 additions & 3 deletions djmoney/contrib/exchange/backends/openexchangerates.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,16 @@


class OpenExchangeRatesBackend(SimpleExchangeBackend):
name = 'openexchangerates.org'
name = "openexchangerates.org"
url = settings.OPEN_EXCHANGE_RATES_URL

def __init__(self, url=settings.OPEN_EXCHANGE_RATES_URL, access_key=settings.OPEN_EXCHANGE_RATES_APP_ID):
if access_key is None:
raise ImproperlyConfigured(
'settings.OPEN_EXCHANGE_RATES_APP_ID should be set to use OpenExchangeRatesBackend'
"settings.OPEN_EXCHANGE_RATES_APP_ID should be set to use OpenExchangeRatesBackend"
)
self.url = url
self.access_key = access_key

def get_params(self):
return {'app_id': self.access_key}
return {"app_id": self.access_key}
2 changes: 0 additions & 2 deletions djmoney/contrib/exchange/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@


class MissingRate(Exception):
"""
Absence of some exchange rate.
Expand Down
9 changes: 5 additions & 4 deletions djmoney/contrib/exchange/management/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,11 @@ class BaseExchangeCommand(BaseCommand):

def add_arguments(self, parser):
parser.add_argument(
'-b', '--backend',
action='store',
dest='backend',
help='Importable string for custom exchange rates backend.',
"-b",
"--backend",
action="store",
dest="backend",
help="Importable string for custom exchange rates backend.",
required=False,
default=settings.EXCHANGE_BACKEND,
)
Expand Down
16 changes: 9 additions & 7 deletions djmoney/contrib/exchange/management/commands/clear_rates.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,25 @@


class Command(BaseExchangeCommand):
help = 'Clears exchange rates.'
help = "Clears exchange rates."

def add_arguments(self, parser):
super(Command, self).add_arguments(parser)
parser.add_argument(
'--all', action='store_true', dest='all',
help='Clear rates for all backends.',
"--all",
action="store_true",
dest="all",
help="Clear rates for all backends.",
required=False,
default=False,
)

def handle(self, *args, **options):
if options['all']:
if options["all"]:
Rate.objects.all().delete()
message = 'Successfully cleared all rates'
message = "Successfully cleared all rates"
else:
backend = import_string(options['backend'])
backend = import_string(options["backend"])
Rate.objects.filter(backend=backend.name).delete()
message = 'Successfully cleared rates for %s' % backend.name
message = "Successfully cleared rates for %s" % backend.name
self.success(message)
6 changes: 3 additions & 3 deletions djmoney/contrib/exchange/management/commands/update_rates.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@


class Command(BaseExchangeCommand):
help = 'Updates exchange rates.'
help = "Updates exchange rates."

def handle(self, *args, **options):
backend = import_string(options['backend'])()
backend = import_string(options["backend"])()
backend.update_rates()
self.success('Successfully updated rates from %s' % backend.name)
self.success("Successfully updated rates from %s" % backend.name)
31 changes: 16 additions & 15 deletions djmoney/contrib/exchange/migrations/0001_initial.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,29 +8,30 @@ class Migration(migrations.Migration):

initial = True

dependencies = [
]
dependencies = []

operations = [
migrations.CreateModel(
name='ExchangeBackend',
name="ExchangeBackend",
fields=[
('name', models.CharField(max_length=255, primary_key=True, serialize=False)),
('last_update', models.DateTimeField(auto_now=True)),
('base_currency', models.CharField(max_length=3)),
("name", models.CharField(max_length=255, primary_key=True, serialize=False)),
("last_update", models.DateTimeField(auto_now=True)),
("base_currency", models.CharField(max_length=3)),
],
),
migrations.CreateModel(
name='Rate',
name="Rate",
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('currency', models.CharField(max_length=3)),
('value', models.DecimalField(decimal_places=6, max_digits=20)),
('backend', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='exchange.ExchangeBackend', related_name='rates')),
("id", models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
("currency", models.CharField(max_length=3)),
("value", models.DecimalField(decimal_places=6, max_digits=20)),
(
"backend",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE, to="exchange.ExchangeBackend", related_name="rates"
),
),
],
),
migrations.AlterUniqueTogether(
name='rate',
unique_together={('currency', 'backend')},
),
migrations.AlterUniqueTogether(name="rate", unique_together={("currency", "backend")}),
]
14 changes: 7 additions & 7 deletions djmoney/contrib/exchange/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,10 @@ def clear_rates(self):
class Rate(models.Model):
currency = models.CharField(max_length=3)
value = models.DecimalField(max_digits=20, decimal_places=6)
backend = models.ForeignKey(ExchangeBackend, on_delete=models.CASCADE, related_name='rates')
backend = models.ForeignKey(ExchangeBackend, on_delete=models.CASCADE, related_name="rates")

class Meta:
unique_together = (('currency', 'backend'), )
unique_together = (("currency", "backend"),)


def get_default_backend_name():
Expand All @@ -43,7 +43,7 @@ def get_rate(source, target, backend=None):
"""
if backend is None:
backend = get_default_backend_name()
key = 'djmoney:get_rate:%s:%s:%s' % (source, target, backend)
key = "djmoney:get_rate:%s:%s:%s" % (source, target, backend)
result = cache.get(key)
if result is not None:
return result
Expand All @@ -56,9 +56,9 @@ def _get_rate(source, target, backend):
source, target = text_type(source), text_type(target)
if text_type(source) == target:
return 1
rates = Rate.objects.filter(currency__in=(source, target), backend=backend).select_related('backend')
rates = Rate.objects.filter(currency__in=(source, target), backend=backend).select_related("backend")
if not rates:
raise MissingRate('Rate %s -> %s does not exist' % (source, target))
raise MissingRate("Rate %s -> %s does not exist" % (source, target))
if len(rates) == 1:
return _try_to_get_rate_directly(source, target, rates[0])
return _get_rate_via_base(rates, target)
Expand All @@ -75,7 +75,7 @@ def _try_to_get_rate_directly(source, target, rate):
elif rate.backend.base_currency == target and rate.currency == source:
return 1 / rate.value
# Case when target or source is not a base currency
raise MissingRate('Rate %s -> %s does not exist' % (source, target))
raise MissingRate("Rate %s -> %s does not exist" % (source, target))


def _get_rate_via_base(rates, target):
Expand All @@ -102,7 +102,7 @@ def _get_rate_via_base(rates, target):


def convert_money(value, currency):
if 'djmoney.contrib.exchange' not in settings.INSTALLED_APPS:
if "djmoney.contrib.exchange" not in settings.INSTALLED_APPS:
raise ImproperlyConfigured(
"You have to add 'djmoney.contrib.exchange' to INSTALLED_APPS in order to use currency exchange"
)
Expand Down
30 changes: 22 additions & 8 deletions djmoney/forms/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,30 @@
from .widgets import MoneyWidget


__all__ = ('MoneyField',)
__all__ = ("MoneyField",)


class MoneyField(MultiValueField):

def __init__(self, currency_widget=None, currency_choices=CURRENCY_CHOICES, max_value=None, min_value=None,
max_digits=None, decimal_places=None, default_amount=None, default_currency=None, *args, **kwargs):
def __init__(
self,
currency_widget=None,
currency_choices=CURRENCY_CHOICES,
max_value=None,
min_value=None,
max_digits=None,
decimal_places=None,
default_amount=None,
default_currency=None,
*args,
**kwargs
):

amount_field = DecimalField(
*args, max_value=max_value, min_value=min_value, max_digits=max_digits, decimal_places=decimal_places,
*args,
max_value=max_value,
min_value=min_value,
max_digits=max_digits,
decimal_places=decimal_places,
**kwargs
)
currency_field = ChoiceField(choices=currency_choices)
Expand All @@ -34,7 +48,7 @@ def __init__(self, currency_widget=None, currency_choices=CURRENCY_CHOICES, max_
self.widget = MoneyWidget(
amount_widget=amount_field.widget,
currency_widget=currency_field.widget,
default_currency=default_currency
default_currency=default_currency,
)
# The two fields that this widget comprises
fields = (amount_field, currency_field)
Expand All @@ -59,10 +73,10 @@ def clean(self, value):

def has_changed(self, initial, data): # noqa
# Django 1.8 has no 'disabled' attribute
if hasattr(self, 'disabled') and self.disabled:
if hasattr(self, "disabled") and self.disabled:
return False
if initial is None:
initial = ['' for _ in range(0, len(data))]
initial = ["" for _ in range(0, len(data))]
else:
if not isinstance(initial, list):
initial = self.widget.decompress(initial)
Expand Down
Loading

0 comments on commit 0184f86

Please sign in to comment.