Skip to content
This repository was archived by the owner on Feb 28, 2020. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 4 additions & 15 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,29 +1,18 @@
language: python
python:
- "3.5"
- "3.7"

sudo: false

env:
- TOXENV=py27-django18
- TOXENV=py27-django19
- TOXENV=py27-django110
- TOXENV=py33-django18
- TOXENV=py34-django18
- TOXENV=py34-django19
- TOXENV=py34-django110
- TOXENV=py34-djangomaster
- TOXENV=py35-django18
- TOXENV=py35-django19
- TOXENV=py35-django110
- TOXENV=py35-djangomaster
- TOXENV=py37-django22
- TOXENV=py37-django30

matrix:
fast_finish: true

install:
- pip install tox "virtualenv<14"
- pip install coveralls
- pip install tox virtualenv coveralls

script:
- tox
Expand Down
2 changes: 1 addition & 1 deletion djmoney_rates/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ class RateInline(admin.TabularInline):
model = Rate


@admin.register(RateSource)
class RateSourceAdmin(admin.ModelAdmin):
inlines = [
RateInline,
]


admin.site.register(RateSource, RateSourceAdmin)
22 changes: 7 additions & 15 deletions djmoney_rates/backends.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,8 @@
from __future__ import unicode_literals

from urllib.request import urlopen
import logging
import json

from django.core.exceptions import ImproperlyConfigured
from django.utils import six

try:
from urllib2 import urlopen
except ImportError:
from urllib.request import urlopen

from .exceptions import RateBackendError
from .models import RateSource, Rate
Expand All @@ -19,7 +12,7 @@
logger = logging.getLogger(__name__)


class BaseRateBackend(object):
class BaseRateBackend:
source_name = None
base_currency = None

Expand Down Expand Up @@ -57,7 +50,7 @@ def update_rates(self):
source.base_currency = self.get_base_currency()
source.save()

for currency, value in six.iteritems(self.get_rates()):
for currency, value in self.get_rates().items():
try:
rate = Rate.objects.get(source=source, currency=currency)
except Rate.DoesNotExist:
Expand All @@ -80,23 +73,22 @@ def __init__(self):
"OPENEXCHANGE_APP_ID setting should not be empty when using OpenExchangeBackend")

# Build the base api url
base_url = "%s?app_id=%s" % (money_rates_settings.OPENEXCHANGE_URL,
money_rates_settings.OPENEXCHANGE_APP_ID)
base_url = f"{money_rates_settings.OPENEXCHANGE_URL}?app_id={money_rates_settings.OPENEXCHANGE_APP_ID}"

# Change the base currency whether it is specified in settings
base_url += "&base=%s" % self.get_base_currency()
base_url += f"&base={self.get_base_currency()}"

self.url = base_url

def get_rates(self):
try:
logger.debug("Connecting to url %s" % self.url)
logger.debug(f"Connecting to url {self.url}")
data = urlopen(self.url).read().decode("utf-8")
return json.loads(data)['rates']

except Exception as e:
logger.exception("Error retrieving data from %s", self.url)
raise RateBackendError("Error retrieving rates: %s" % e)
raise RateBackendError(f"Error retrieving rates: {e}")

def get_base_currency(self):
return money_rates_settings.OPENEXCHANGE_BASE_CURRENCY
8 changes: 3 additions & 5 deletions djmoney_rates/management/commands/update_rates.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from __future__ import unicode_literals

from django.core.management.base import BaseCommand, CommandError

from ...settings import money_rates_settings, import_from_string
Expand All @@ -16,14 +14,14 @@ def handle(self, *args, **options):
try:
backend_class = import_from_string(options['backend_path'], "")
except ImportError:
raise CommandError("Cannot find custom backend %s. Is it correct" % options['backend_path'])
raise CommandError("Cannot find custom backend {}. Is it correct".format(options['backend_path']))
else:
backend_class = money_rates_settings.DEFAULT_BACKEND

try:
backend = backend_class()
backend.update_rates()
except Exception as e:
raise CommandError("Error during rate update: %s" % e)
raise CommandError(f"Error during rate update: {e}")

self.stdout.write('Successfully updated rates for "%s"' % backend_class)
self.stdout.write(f'Successfully updated rates for "{backend_class}"')
41 changes: 41 additions & 0 deletions djmoney_rates/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Generated by Django 1.11.2 on 2017-06-09 17:25

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

initial = True

dependencies = [
]

operations = [
migrations.CreateModel(
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)),
],
),
migrations.CreateModel(
name='RateSource',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100, unique=True)),
('last_update', models.DateTimeField(auto_now=True)),
('base_currency', models.CharField(max_length=3)),
],
),
migrations.AddField(
model_name='rate',
name='source',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='djmoney_rates.RateSource'),
),
migrations.AlterUniqueTogether(
name='rate',
unique_together=set([('source', 'currency')]),
),
]
Empty file.
7 changes: 1 addition & 6 deletions djmoney_rates/models.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
from __future__ import unicode_literals

from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _


@python_2_unicode_compatible
class RateSource(models.Model):
name = models.CharField(max_length=100, unique=True)
last_update = models.DateTimeField(auto_now=True)
Expand All @@ -16,7 +12,6 @@ def __str__(self):
self.name, self.base_currency, self.last_update)


@python_2_unicode_compatible
class Rate(models.Model):
source = models.ForeignKey(RateSource, on_delete=models.CASCADE)
currency = models.CharField(max_length=3)
Expand Down
19 changes: 6 additions & 13 deletions djmoney_rates/settings.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from __future__ import unicode_literals

"""
This module is largely inspired by django-rest-framework settings.

Expand All @@ -16,12 +14,7 @@
"""

from django.conf import settings

try:
from django.utils import importlib, six
except ImportError:
import importlib
import six
import importlib


USER_SETTINGS = getattr(settings, 'DJANGO_MONEY_RATES', None)
Expand Down Expand Up @@ -50,7 +43,7 @@ def perform_import(val, setting_name):
If the given setting is a string import notation,
then perform the necessary import or imports.
"""
if isinstance(val, six.string_types):
if isinstance(val, str):
return import_from_string(val, setting_name)
elif isinstance(val, (list, tuple)):
return [import_from_string(item, setting_name) for item in val]
Expand All @@ -67,11 +60,11 @@ def import_from_string(val, setting_name):
module = importlib.import_module(module_path)
return getattr(module, class_name)
except ImportError as e:
msg = "Could not import '%s' for setting '%s'. %s: %s." % (val, setting_name, e.__class__.__name__, e)
msg = f"Could not import '{val}' for setting '{setting_name}'. {e.__class__.__name__}: {e}."
raise ImportError(msg)


class MoneyRatesSettings(object):
class MoneyRatesSettings:
"""
A settings object, that allows Bazaar settings to be accessed as properties.

Expand All @@ -87,7 +80,7 @@ def __init__(self, user_settings=None, defaults=None, import_strings=None, manda

def __getattr__(self, attr):
if attr not in self.defaults.keys():
raise AttributeError("Invalid django-money-rates setting: '%s'" % attr)
raise AttributeError(f"Invalid django-money-rates setting: '{attr}'")

try:
# Check if present in user settings
Expand All @@ -108,7 +101,7 @@ def __getattr__(self, attr):

def validate_setting(self, attr, val):
if not val and attr in self.mandatory:
raise AttributeError("django-money-rates setting: '%s' is mandatory" % attr)
raise AttributeError(f"django-money-rates setting: '{attr}' is mandatory")


money_rates_settings = MoneyRatesSettings(USER_SETTINGS, DEFAULTS, IMPORT_STRINGS, MANDATORY)
11 changes: 4 additions & 7 deletions djmoney_rates/utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from __future__ import unicode_literals

from decimal import Decimal

from .exceptions import CurrencyConversionException
Expand All @@ -16,9 +14,8 @@ def get_rate(currency):
return Rate.objects.get(source=source, currency=currency).value
except Rate.DoesNotExist:
raise CurrencyConversionException(
"Rate for %s in %s do not exists. "
"Please run python manage.py update_rates" % (
currency, source.name))
f"Rate for {currency} in {source.name} do not exists. "
"Please run python manage.py update_rates")


def get_rate_source():
Expand All @@ -28,8 +25,8 @@ def get_rate_source():
return RateSource.objects.get(name=backend.get_source_name())
except RateSource.DoesNotExist:
raise CurrencyConversionException(
"Rate for %s source do not exists. "
"Please run python manage.py update_rates" % backend.get_source_name())
f"Rate for {backend.get_source_name()} source do not exists. "
"Please run python manage.py update_rates")


def base_convert_money(amount, currency_from, currency_to):
Expand Down
17 changes: 8 additions & 9 deletions docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# complexity documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
Expand Down Expand Up @@ -46,8 +45,8 @@
master_doc = 'index'

# General information about the project.
project = u'django-money-rates'
copyright = u'2013, Federico Frenguelli'
project = 'django-money-rates'
copyright = '2013, Federico Frenguelli'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
Expand Down Expand Up @@ -192,8 +191,8 @@
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'django-money-rates.tex', u'django-money-rates Documentation',
u'Federico Frenguelli', 'manual'),
('index', 'django-money-rates.tex', 'django-money-rates Documentation',
'Federico Frenguelli', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
Expand Down Expand Up @@ -222,8 +221,8 @@
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'django-money-rates', u'django-money-rates Documentation',
[u'Federico Frenguelli'], 1)
('index', 'django-money-rates', 'django-money-rates Documentation',
['Federico Frenguelli'], 1)
]

# If true, show URL addresses after external links.
Expand All @@ -236,8 +235,8 @@
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'django-money-rates', u'django-money-rates Documentation',
u'Federico Frenguelli', 'django-money-rates', 'One line description of project.',
('index', 'django-money-rates', 'django-money-rates Documentation',
'Federico Frenguelli', 'django-money-rates', 'One line description of project.',
'Miscellaneous'),
]

Expand Down
9 changes: 4 additions & 5 deletions requirements-test.txt
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
py-moneyed==0.6.0
mock>=1.0.1
pytest-mock==1.2
pytest==2.9.2
pytest-django==3.1.2

pytest-mock
pytest
pytest-django
pytest-cov

# Additional test requirements go here
2 changes: 0 additions & 2 deletions requirements.txt

This file was deleted.

5 changes: 1 addition & 4 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from setuptools import setup, find_packages
import os
Expand Down Expand Up @@ -50,8 +49,6 @@ def get_version(package):
packages=find_packages(),
include_package_data=True,
test_suite='runtests',
install_requires=[
'py-moneyed==0.6.0'
],
install_requires=["py-moneyed>=0.6.0"],
zip_safe=False,
)
4 changes: 1 addition & 3 deletions tests/test_backends.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
from __future__ import unicode_literals

from decimal import Decimal
import pytest

from django.core.exceptions import ImproperlyConfigured

from mock import patch
from unittest.mock import patch

from djmoney_rates.backends import BaseRateBackend, RateBackendError, OpenExchangeBackend
from djmoney_rates.models import Rate, RateSource
Expand Down
2 changes: 0 additions & 2 deletions tests/test_commands.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from __future__ import unicode_literals

import pytest

from django.core.management import call_command
Expand Down
2 changes: 0 additions & 2 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from __future__ import unicode_literals

from decimal import Decimal

import pytest
Expand Down
Loading