Skip to content
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ coverage
.vagrant
manifests/build
*.db
venv
24 changes: 21 additions & 3 deletions exchange/adapters/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ def update(self):
target.code,
usd_exchange_rates)

if rate == False:
continue

exchange_rate = ExchangeRate(source=source,
target=target,
rate=rate)
Expand All @@ -66,10 +69,25 @@ def update(self):
def _get_rate_through_usd(self, source, target, usd_rates):
# from: https://openexchangerates.org/documentation#how-to-use
# gbp_hkd = usd_hkd * (1 / usd_gbp)
usd_source = usd_rates[source]
usd_target = usd_rates[target]
error = False

try:
usd_source = usd_rates[source]
except KeyError:
Currency.objects.filter(code=source).delete()
error = True

try:
usd_target = usd_rates[target]
except KeyError:
Currency.objects.filter(code=target).delete()
error = True

if error:
return False

rate = usd_target * (Decimal(1.0) / usd_source)
rate = rate.quantize(Decimal('0.123456')) # round to 6 decimal places
rate = rate.quantize(Decimal('0.12345678')) # round to 8 decimal places
return rate

def get_currencies(self):
Expand Down
4 changes: 2 additions & 2 deletions exchange/cache.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from django.core.cache import get_cache
from django.core.cache import caches
from django.conf import settings

from exchange.models import ExchangeRate
Expand All @@ -20,7 +20,7 @@

CACHE_TIMEOUT = 0 # Not configurable at all

cache = get_cache(CACHE_DATABASE)
cache = caches[CACHE_DATABASE]


def _get_cache_key(source_currency, target_currency):
Expand Down
88 changes: 36 additions & 52 deletions exchange/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -1,53 +1,37 @@
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models


class Migration(SchemaMigration):

def forwards(self, orm):
# Adding model 'Currency'
db.create_table(u'exchange_currency', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('code', self.gf('django.db.models.fields.CharField')(unique=True, max_length=3)),
('name', self.gf('django.db.models.fields.CharField')(max_length=64)),
))
db.send_create_signal(u'exchange', ['Currency'])

# Adding model 'ExchangeRate'
db.create_table(u'exchange_exchangerate', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('source', self.gf('django.db.models.fields.related.ForeignKey')(related_name='rates', to=orm['exchange.Currency'])),
('target', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['exchange.Currency'])),
('rate', self.gf('django.db.models.fields.DecimalField')(max_digits=12, decimal_places=2)),
))
db.send_create_signal(u'exchange', ['ExchangeRate'])


def backwards(self, orm):
# Deleting model 'Currency'
db.delete_table(u'exchange_currency')

# Deleting model 'ExchangeRate'
db.delete_table(u'exchange_exchangerate')


models = {
u'exchange.currency': {
'Meta': {'object_name': 'Currency'},
'code': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '3'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '64'})
},
u'exchange.exchangerate': {
'Meta': {'object_name': 'ExchangeRate'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'rate': ('django.db.models.fields.DecimalField', [], {'max_digits': '12', 'decimal_places': '2'}),
'source': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'rates'", 'to': u"orm['exchange.Currency']"}),
'target': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['exchange.Currency']"})
}
}

complete_apps = ['exchange']
# Generated by Django 1.9.5 on 2016-04-06 09:33
from __future__ import unicode_literals

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


class Migration(migrations.Migration):

initial = True

dependencies = [
]

operations = [
migrations.CreateModel(
name='Currency',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('code', models.CharField(max_length=3, unique=True)),
('name', models.CharField(max_length=64)),
],
options={
'verbose_name_plural': 'currencies',
},
),
migrations.CreateModel(
name='ExchangeRate',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('rate', models.DecimalField(decimal_places=8, max_digits=17)),
('source', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='rates', to='exchange.Currency')),
('target', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='exchange.Currency')),
],
),
]
20 changes: 20 additions & 0 deletions exchange/migrations/0002_auto_20180802_1451.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2018-08-02 14:51
from __future__ import unicode_literals

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('exchange', '0001_initial'),
]

operations = [
migrations.AlterField(
model_name='exchangerate',
name='rate',
field=models.DecimalField(decimal_places=8, max_digits=20),
),
]
36 changes: 0 additions & 36 deletions exchange/migrations/0002_auto__chg_field_exchangerate_rate.py

This file was deleted.

2 changes: 1 addition & 1 deletion exchange/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class ExchangeRate(models.Model):
"""Model to persist exchange rates between currencies"""
source = models.ForeignKey('exchange.Currency', related_name='rates')
target = models.ForeignKey('exchange.Currency')
rate = models.DecimalField(max_digits=17, decimal_places=8)
rate = models.DecimalField(max_digits=20, decimal_places=8)

objects = ExchangeRateManager()

Expand Down
39 changes: 30 additions & 9 deletions exchange/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def import_class(class_path):
'OrderedDict'
"""
try:
from django.utils.importlib import import_module
from importlib import import_module
module_name = '.'.join(class_path.split(".")[:-1])
mod = import_module(module_name)
return getattr(mod, class_path.split(".")[-1])
Expand Down Expand Up @@ -52,9 +52,18 @@ def insert_many(objects, using="default"):
table = model._meta.db_table
column_names = ",".join(con.ops.quote_name(f.column) for f in fields)
placeholders = ",".join(("%s",) * len(fields))
con.cursor().executemany("insert into %s (%s) values (%s)"
% (table, column_names, placeholders), parameters)
transaction.commit_unless_managed(using=using)

from distutils.version import StrictVersion
from django import get_version
# see https://docs.djangoproject.com/en/1.9/internals/deprecation/#deprecation-removed-in-1-8
if StrictVersion(get_version()) >= StrictVersion('1.6.0'):
with transaction.atomic():
con.cursor().executemany("insert into %s (%s) values (%s)"
% (table, column_names, placeholders), parameters)
else:
con.cursor().executemany("insert into %s (%s) values (%s)"
% (table, column_names, placeholders), parameters)
transaction.commit_unless_managed(using=using)


def update_many(objects, fields=[], using="default"):
Expand Down Expand Up @@ -91,11 +100,23 @@ def update_many(objects, fields=[], using="default"):
table = meta.db_table
assignments = ",".join(("%s=%%s" % con.ops.quote_name(f.column))
for f in fields)
con.cursor().executemany("update %s set %s where %s=%%s"
% (table, assignments,
con.ops.quote_name(meta.pk.column)),
parameters)
transaction.commit_unless_managed(using=using)

from distutils.version import StrictVersion
from django import get_version
# see https://docs.djangoproject.com/en/1.9/internals/deprecation/#deprecation-removed-in-1-8
if StrictVersion(get_version()) >= StrictVersion('1.6.0'):
with transaction.atomic():
con.cursor().executemany("update %s set %s where %s=%%s"
% (table, assignments,
con.ops.quote_name(meta.pk.column)),
parameters)
else:
con.cursor().executemany("update %s set %s where %s=%%s"
% (table, assignments,
con.ops.quote_name(meta.pk.column)),
parameters)
transaction.commit_unless_managed(using=using)



def memoize(ttl=None):
Expand Down
11 changes: 10 additions & 1 deletion test_project/settings.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
INSTALLED_APPS = ['exchange']
DEBUG = True

SECRET_KEY = 'fake-key'

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'exchange'
]

DATABASES = {
'default': {
Expand Down