def index():
    if 'from' not in request.args or 'to' not in request.args or 'amount' not in request.args:
        return jsonify({"error": "Arguments missing"}), 412

    currency_from = request.args.get('from')
    currency_to = request.args.get('to')
    amount = request.args.get('amount')

    try:
        amount = float(amount)
    except:
        return jsonify({"error": "Invalid Amount Format"}), 412

    c1 = Currency()
    c2 = Currency()

    c_from = c1.find_by_symbol(currency_from)
    c_to = c2.find_by_symbol(currency_to)

    # Verifico a existencia das moedas no banco
    if not c_to or not c_from:
        return jsonify({"error": "Currency not Found"}), 404
    if "value" not in c_from or "value" not in c_from:
        return jsonify({"error": "Currency not Found"}), 404

    # Ex: valor convertido = (valorBRL / valorEUR) * valor a converter
    converted_amount = (c_to["value"] / c_from["value"]) * amount

    json_res = {
        "original": {
            "currency": currency_from,
            "value": amount
        },
        "converted": {
            "currency": currency_to,
            "value": converted_amount
        },
        "_links": {
            "url": request.url,
            "list_all_currencys": request.url_root + "currencies",
            "usd_to_currency_from":
            request.url_root + "currencies/" + currency_from,
            "usd_to_currency_to":
            request.url_root + "currencies/" + currency_to,
        }
    }

    return jsonify(json_res), 200
示例#2
0
def test_index_result(client):
    currency_from = 'BRL'
    currency_to = 'EUR'
    amount = 150

    c1 = Currency()
    c2 = Currency()

    c_from = c1.find_by_symbol(currency_from)
    c_to = c2.find_by_symbol(currency_to)

    expected_result = (c_to["value"] / c_from["value"]) * amount

    res = client.get('/?from={0}&to={1}&amount={2}'.format(
        currency_from, currency_to, amount))
    result_json = res.get_json()

    assert res.status_code == 200

    assert result_json['original']['currency'] == currency_from
    assert result_json['original']['value'] == amount

    assert result_json['converted']['currency'] == currency_to
    assert result_json['converted']['value'] == expected_result
def get_all_currencies(symbol):
    c = Currency()
    return c.find_by_symbol(symbol), 200