コード例 #1
0
ファイル: test_models.py プロジェクト: clybob/challenge-bravo
    def test_instance_should_have_save_method(self):
        currency = Currency('BRL', 2.0)
        currency.save()

        rate = Redis.hget('currencies', 'BRL')

        self.assertTrue(rate)
コード例 #2
0
    def test_count_query_on_get_currencies_serializer(self):
        for i in range(1, 10):
            currency = Currency.objects.create(name=f'currency{i}')
            Scraper.objects.create(currency=currency, frequency=i)
            currency.prices.create(value=i)

        with self.assertNumQueries(11):
            Currency.get_currencies_serializer()
コード例 #3
0
    def test_delete_currency(self):
        currency = Currency.objects.create(name='Bitcoin')

        data = {
            'id': currency.pk,
        }

        Currency.delete_currency(data)
        self.assertEqual(Currency.objects.count(), 0)
コード例 #4
0
    def test_delete_currency_invalid_id(self):
        self.assertEqual(
            Currency.objects.count(),
            0
        )

        data = {
            'id': 1,
        }

        with self.assertRaises(Currency.DoesNotExist):
            Currency.delete_currency(data)
コード例 #5
0
    def test_delete_currency_invalid_data(self):
        self.assertEqual(
            Currency.objects.count(),
            0
        )

        data = {
            'invalid-key': 1,
        }

        with self.assertRaises(ValidationError):
            Currency.delete_currency(data)
コード例 #6
0
    def test_create_currency_from_coinmarketcap_invalid_currency(self):
        data = {
            'currency': 'invalid-currency-foo',
            'frequency': 20,
        }

        with self.assertRaises(HTTPError):
            Currency.create_currency_from_coinmarketcap(data)

        self.assertEqual(
            Currency.objects.count(),
            0
        )
コード例 #7
0
    def test_update_frequency(self):
        currency = Currency.objects.create(name='Bitcoin')
        Scraper.objects.create(currency=currency, frequency=60)

        data = {
            'id': currency.pk,
            'frequency': 20,
        }

        Currency.update_frequency(data)

        currency.refresh_from_db()
        self.assertEqual(currency.frequency, data['frequency'])
コード例 #8
0
    def test_update_frequency_invalid_id(self):
        self.assertEqual(
            Currency.objects.count(),
            0
        )

        data = {
            'id': 1,
            'frequency': 20,
        }

        with self.assertRaises(Currency.DoesNotExist):
            Currency.update_frequency(data)
コード例 #9
0
    def test_update_frequency_invalid_data(self):
        self.assertEqual(
            Currency.objects.count(),
            0
        )

        data = {
            'id': 1,
            'invalid-key': 20,
        }

        with self.assertRaises(ValidationError):
            Currency.update_frequency(data)
コード例 #10
0
    def test_create_currency_from_coinmarketcap_invalid_data(self):
        data = {
            'foo': 'Bitcoin',
            'bar': 20,
        }

        with self.assertRaises(ValidationError):
            Currency.create_currency_from_coinmarketcap(data)

        self.assertEqual(
            Currency.objects.count(),
            0
        )
コード例 #11
0
ファイル: views.py プロジェクト: airsoull/RG
 def post(self, *args, **kwargs):
     try:
         data = self.get_data()
         return JsonResponse(
             Currency.create_currency_from_coinmarketcap(data=data))
     except Exception as e:
         return self.get_bad_request(e)
コード例 #12
0
    def test_create_currency_from_coinmarketcap(self):
        self.assertEqual(
            Currency.objects.count(),
            0
        )

        data = {
            'currency': 'Bitcoin',
            'frequency': 20,
        }

        data = Currency.create_currency_from_coinmarketcap(data)
        self.assertEqual(
            Currency.objects.count(),
            1
        )

        currency = Currency.objects.get()

        self.assertEqual(currency.name, data['currency'])
        self.assertEqual(currency.frequency, data['frequency'])
        self.assertEqual(currency.prices.count(), 1)
        self.assertEqual(
            sorted(data.keys()),
            sorted(currency.get_currency_retrieve_serializer().keys())
        )
コード例 #13
0
ファイル: views.py プロジェクト: mavhungu2/django-api
def currencies(request):
    if request.method == "PUT":
        # Update database with latest currencies
        try:
            rates = requests.get("https://api.exchangeratesapi.io/latest?base=ZAR").json()['rates']
            print(rates)
            Currency.objects.all().delete()
            for name, value in rates.items():
                print(name)
                print(value)
                Currency(name=name, value=value).save()
        except requests.exceptions.RequestException as e:
            # Show error if failed to connect to api
            return JsonResponse({"code": 200, "message": "Connection Error, Currencies May Not Be The Latest"})
        return JsonResponse({"code": 200, "message": "Updated Currencies"})

    if request.method == "GET":
        currencies = Currency.objects.all()
        serializer = CurrencySerializer(currencies, many=True)
        return JsonResponse(dict(currencies=list(serializer.data)))

    if request.method == "POST":
        try:
            value1 = Currency.objects.get(name=request.GET['currency'])
            print(value1)
        except Currency.DoesNotExist:
            return JsonResponse({"code": 404, "message": "Currency Does Not Exist"})
        value = CurrencySerializer(value1).data['value']
        print(value)
        return JsonResponse({"result" : float(request.GET['value'])/value})
コード例 #14
0
    def test_create_currency_from_coinmarketcap_not_repeat_currency(self):
        data = {
            'currency': 'Bitcoin',
            'frequency': 20,
        }

        Currency.create_currency_from_coinmarketcap(data)
        currency = Currency.objects.first()

        Currency.create_currency_from_coinmarketcap(data)
        currency2 = Currency.objects.last()

        self.assertEqual(
            Currency.objects.count(),
            1
        )
        self.assertEqual(currency, currency2)
        self.assertEqual(currency.value, currency2.value)
コード例 #15
0
    def put(self, request):

        # I get the content from the body request and convert it into a dictionary
        body_unicode = request.body.decode('utf-8')
        body = json.loads(body_unicode)

        try:
            # Define what the prototype is for a user and grab data from the dictionary
            newCurrency = Currency(
                name=body['name'],
                symbol=body['symbol'],
                rank=body['rank'],
                price_usd=body['price_usd'],
                volume_24h_usd=body['volume_24h_usd'],
                market_cap_usd=body['market_cap_usd'],
                available_supply=body['available_supply'],
                total_supply=body['total_supply'],
                percent_change_1h=body['percent_change_1h'],
                percent_change_24h=body['percent_change_24h'],
                percent_change_7d=body['percent_change_7d'],
                last_updated=body['last_updated'],
                ticker_history=body['ticker_history'])

            # Save the new coin
            newCurrency.save()

        except Exception as e:
            logger.error('Something went wrong!')
            # Custom error message to return if coin could not be created
            raise ObjectNotFound("Could not create the coin {}".format(e))

        # Serialize the new coin data
        serializer = CurrencySerializer(newCurrency, many=False)

        # Return the coin
        return Response(serializer.data)
コード例 #16
0
ファイル: util.py プロジェクト: iamanikeev/currency-convert
def build_currency_rates(queryset):
    rates = get_rates_from_openexchange()
    now = int(datetime.now().timestamp())
    # Add base (USD) api
    usd = Currency(base='USD', created_timestamp=now)
    usd.save()

    for code, rate_to_usd in rates.items():
        rate_to_usd = Decimal(rate_to_usd)
        # Add corresponding rates for USD
        Rate(base=usd, code=code, rate=rate_to_usd).save()

        # Add each of allowed currencies and populate its rates
        curr = Currency(base=code, created_timestamp=now)
        curr.save()
        Rate(base=curr, code='USD', rate=Decimal(1) / rate_to_usd).save()
        for curr_code, rate_to_curr in (_ for _ in rates.items()
                                        if _[0] != code):
            Rate(base=curr,
                 code=curr_code,
                 rate=Decimal(1) / rate_to_usd * Decimal(rate_to_curr)).save()
    return queryset.all()
コード例 #17
0
ファイル: views.py プロジェクト: airsoull/RG
 def delete(self, *args, **kwargs):
     try:
         data = self.get_data()
         return JsonResponse(Currency.delete_currency(data=data))
     except Exception as e:
         return self.get_bad_request(e)
コード例 #18
0
ファイル: test_models.py プロジェクト: clybob/challenge-bravo
    def test_instance_should_be_renderized_in_dict(self):
        currency = Currency('BRL', 2.0)
        currency_json = currency.to_dict()

        self.assertEqual(currency_json, {'id': 'BRL', 'rate': 2.0})
コード例 #19
0
ファイル: test_models.py プロジェクト: clybob/challenge-bravo
    def test_instance_model_should_create_new_object(self):
        currency = Currency('BRL', 2.0)

        self.assertIsInstance(currency, Currency)
        self.assertEqual(currency.currency_id, 'BRL')
        self.assertEqual(currency.rate, 2.0)
コード例 #20
0
ファイル: views.py プロジェクト: airsoull/RG
 def get(self, *args, **kwargs):
     return JsonResponse(Currency.get_currencies_serializer())