def test_convert_using_division():
    assert(convert(
        rates=[("USD", "EUR", 0.74)], value=1, current='EUR',
        to='USD')) == 1 / 0.74
    assert(convert(
        rates=[("EUR", "JPY", 129.24)], value=2, current='JPY',
        to='EUR')) == 2 / 129.24
def test_convert_using_multiplication():
    assert(convert(
        rates=[("USD", "EUR", 0.74)], value=1, current='USD',
        to='EUR')) == 0.74
    assert(convert(
        rates=[("EUR", "JPY", 129.24)], value=3, current='EUR',
        to='JPY')) == 3 * 129.24
Esempio n. 3
0
 def convert_home_to_selected(
         self
 ):  #conversion upon getting an amount at home country textinput
     try:
         self.converted_amount_ts = currency.convert(
             self.root.ids.input_home.text, self.home_country_details[1],
             self.selected_country_details[1])  #a.
         self.root.ids.input_selected.text = str(
             ("{:.3f}".format(self.converted_amount_ts)))  #b.
         self.root.ids.status_bar.text = str("{} ({}) to {} ({})".format(
             self.home_country_details[1], self.home_country_details[2],
             self.selected_country_details[1],
             self.selected_country_details[2]))  #c.
     except:  #if no selection on spinner then current country according to the current date is taken
         self.get_current_country_details(
         )  #gettings the current country details
         self.root.ids.spinner_selection.text = self.current_country  #assigning the current country name to spinner text
         self.converted_amount_ts = currency.convert(
             self.root.ids.input_home.text, self.home_country_details[1],
             self.current_country_details[1])  #a.
         self.root.ids.input_selected.text = str(
             ("{:.3f}".format(self.converted_amount_ts)))  #b.
         self.root.ids.status_bar.text = str("{} ({}) to {} ({})".format(
             self.home_country_details[1], self.home_country_details[2],
             self.selected_country_details[1],
             self.selected_country_details[2]))  #c.
Esempio n. 4
0
    def handle_update_button(self):
        localtime = time.strftime("%H:%M:%S")
        self.enable_app()
        # self.handle_currency_input()
        if self.root.ids.country_selector.text == "":
            user_country = self.current_country
            self.root.ids.country_selector.text = user_country
            self.root.ids.home_currency_input.text = ""

        self.cached_conversion_rate = {}
        country_information = self.trip_details
        selected_country = self.root.ids.country_selector.text

        home_country_information = (country_information.get(self.root.ids.home_country.text.strip("\n")))
        home_country_code = home_country_information[1]

        away_country_information = country_information.get(selected_country)
        away_country_code = (away_country_information[1])

        for countries in self.saved_trips:
            country_codes = country_information.get(countries)
            stored_code = country_codes[1]
            stored_rate = currency.convert(1, country_codes[1], home_country_code)
            self.cached_conversion_rate[countries] = stored_rate
            if stored_code == away_country_code:
                pass
            else:
                stored_rate = currency.convert(1, country_codes[1], home_country_code)
                self.cached_conversion_rate[countries] = stored_rate

        self.root.ids.status_field.text = "Last updated: " + localtime
    def change_amount(self):
        self.currency1 = self.root.ids.input_home_country_amount.text
        self.currency2 = self.root.ids.input_country_amount.text

        self.root.ids.input_country_amount.focus = False
        self.root.ids.input_home_country_amount.focus = False

        if self.currency1 is "":
            self.amount2 = currency.convert(self.currency2,
                                            self.country_details2[1],
                                            self.country_details1[1])
            self.amount2 = round(self.amount2, 3)
            print(self.amount2)
            if self.amount2 is -1:
                self.root.ids.input_country_amount.disabled = True
                self.root.ids.input_home_country_amount.disabled = True
            self.root.ids.input_home_country_amount.text = str(self.amount2)
            self.root.ids.status.text = "{}({}) -> {}({})".format(
                self.country_details2[1], self.country_details2[2],
                self.country_details1[1], self.country_details1[2])

        elif self.currency2 is "":
            self.amount1 = currency.convert(self.currency1,
                                            self.country_details1[1],
                                            self.country_details2[1])
            self.amount1 = round(self.amount1, 3)
            print(self.amount1)
            if self.amount1 is -1:
                self.root.ids.input_country_amount.disabled = True
                self.root.ids.input_home_country_amount.disabled = True
            self.root.ids.input_country_amount.text = str(self.amount1)
            self.root.ids.status.text = "{}({}) -> {}({})".format(
                self.country_details1[1], self.country_details1[2],
                self.country_details2[1], self.country_details2[2])
def test_convert_multiple_rates():
    rates = [("USD", "EUR", 0.74), ("EUR", "JPY", 145.949)]
    assert round(convert(rates, value=10, current='USD', to='EUR'), 2) == 7.4
    assert round(convert(rates, value=10, current='EUR', to='USD'), 2) == 13.51
    assert round(convert(rates, value=10, current='EUR', to='JPY'),
                 2) == 1459.49
    assert round(convert(rates, value=100, current='JPY', to='EUR'), 2) == 0.69
def test_convert_muliple_rates():
    rates=[('USD', 'EUR', 0.74)], ("EUR", "JPY", 145.949)]
    (['USD', 'EUR', 0.74])[]
    assert round(convert(rates, value = 10, current = 'USD', to = 'EUR'), 2) == 7.4
    assert round(convert(rates, value = 10, current = 'EUR', to = 'JPY'), 2) == 145.949
    assert round(convert(rates, value = 10, current = 'EUR', to = 'USD'), 2) == 13.51
    assert round(convert(rates, value = 100, current = 'JPY', to = 'EUR'), 2) == .69
def test_convert_forward():
    assert convert(
        rates=[("USD", "EUR", 0.74)], value=1, current='USD', to='EUR') == 0.74
    assert round(
        convert(
            rates=[("USD", "EUR", 0.74)], value=3, current='USD', to='EUR'),
        2) == 2.22
    def change_amount(self):
        self.currency1 = self.root.ids.input_home_country_amount.text
        self.currency2 = self.root.ids.input_country_amount.text

        self.root.ids.input_country_amount.focus = False
        self.root.ids.input_home_country_amount.focus = False

        if self.currency1 is "":
            self.amount2 = currency.convert(self.currency2, self.country_details2[1], self.country_details1[1])
            self.amount2 = round(self.amount2, 3)
            print(self.amount2)
            if self.amount2 is -1:
                self.root.ids.input_country_amount.disabled = True
                self.root.ids.input_home_country_amount.disabled = True
            self.root.ids.input_home_country_amount.text = str(self.amount2)
            self.root.ids.status.text = "{}({}) -> {}({})".format(self.country_details2[1],  self.country_details2[2], self.country_details1[1], self.country_details1[2])

        elif self.currency2 is "":
            self.amount1 = currency.convert(self.currency1, self.country_details1[1], self.country_details2[1])
            self.amount1 = round(self.amount1, 3)
            print(self.amount1)
            if self.amount1 is -1:
                self.root.ids.input_country_amount.disabled = True
                self.root.ids.input_home_country_amount.disabled = True
            self.root.ids.input_country_amount.text = str(self.amount1)
            self.root.ids.status.text = "{}({}) -> {}({})".format(self.country_details1[1],  self.country_details1[2],  self.country_details2[1], self.country_details2[2])
def test_convert_multiple_rates():
    rates = [("USD", "EUR", 0.74), ("EUR", "JPY", 129.24)]
    assert round(convert(rates, value=5, current='USD', to='EUR'), 2) == 3.7
    assert round(convert(rates, value=7, current='EUR', to='USD'), 2) == 9.46
    assert round(
        convert(rates, value=9, current='EUR', to='JPY'), 2) == 1163.35
    assert round(convert(rates, value=11, current='JPY', to='EUR'), 2) == 0.085
Esempio n. 11
0
 def get_currency_conversion(self):
     self.conversion_factor = float(
         currency.convert(1, self.home_country_tuple[1],
                          self.from_country_tuple[1]))
     self.reverse_conversion_factor = float(
         currency.convert(1, self.from_country_tuple[1],
                          self.home_country_tuple[1]))
     print(self.conversion_factor)
Esempio n. 12
0
def test_many_rates():
    assert convert(
        rate = [("USD", "EUR", 0.74), ("EUR", "JPY", 145.949)], value = 1, current = "USD", to = "EUR") == 0.74
    assert round(convert(
        rate = [("USD", "EUR", 0.74), ("EUR", "JPY", 145.949)], value = 1, current = "EUR", to = "USD"), 2) == 1.35
    assert convert(
        rate = [("USD", "EUR", 0.74), ("EUR", "JPY", 145.949)], value = 1, current = "EUR", to = "JPY") == 145.949
    assert round (convert(
        rate = [("USD", "EUR", 0.74), ("EUR", "JPY", 145.949)], value = 1, current = "JPY", to = "EUR"), 5) == 0.00685
Esempio n. 13
0
    def update_currency(self):
        # text input enable
        if self.root.ids.input_country_amount.disabled is True and self.root.ids.input_home_country_amount.disabled is True:
            self.root.ids.input_country_amount.disabled = False
            self.root.ids.input_home_country_amount.disabled = False
            self.root.ids.input_country_amount.text = ''
            self.root.ids.input_home_country_amount.text = ''
            return

        self.root.ids.input_country_amount.focus = False
        self.root.ids.input_home_country_amount.focus = False

        # currency exchange
        self.currency1 = self.root.ids.input_home_country_amount.text
        self.currency2 = self.root.ids.input_country_amount.text

        # spinner / home country name grabbing
        self.country1 = self.root.ids.home_country_label.text
        self.country2 = self.root.ids.country_selection.text

        # checks if spinner selection is blank
        if self.country2 is "":
            self.country2 = self.root.ids.country_selection.text = self.current_location

        # gets country details
        self.country_details1 = currency.get_details(self.country1)
        self.country_details2 = currency.get_details(self.country2)

        # checks to see if there was an inputted currency in the "home country" textbox, if there is no value, then it is assumed that the spinner country textbox has an inputted value.
        if self.currency1 is "":
            self.amount2 = currency.convert(self.currency2,
                                            self.country_details2[1],
                                            self.country_details1[1])
            print(self.amount2)
            self.amount2 = round(self.amount2, 3)
            if self.amount2 is -1:
                self.root.ids.input_country_amount.disabled = True
                self.root.ids.input_home_country_amount.disabled = True
            self.root.ids.input_home_country_amount.text = str(self.amount2)
            current_time = time.strftime("%H:%M:%S")
            self.root.ids.status.text = "updated at {}".format(current_time)

        # checks to see if there was an inputted currency in the spinner country textbox, if there is no value, then it is assumed that the "home country" textbox has an inputted value.
        elif self.currency2 is "":
            self.amount1 = currency.convert(self.currency1,
                                            self.country_details1[1],
                                            self.country_details2[1])
            self.amount1 = round(self.amount1, 3)
            print(self.amount1)
            if self.amount1 is -1:
                self.root.ids.input_country_amount.disabled = True
                self.root.ids.input_home_country_amount.disabled = True
            self.root.ids.input_country_amount.text = str(self.amount1)
            current_time = time.strftime("%H:%M:%S")
            self.root.ids.status.text = "updated at {}".format(current_time)
Esempio n. 14
0
    def update_currency(self):
        # text input enable
        if self.root.ids.input_country_amount.disabled is True and self.root.ids.input_home_country_amount.disabled is True:
            self.root.ids.input_country_amount.disabled = False
            self.root.ids.input_home_country_amount.disabled = False
            self.root.ids.input_country_amount.text = ''
            self.root.ids.input_home_country_amount.text = ''
            return

        self.root.ids.input_country_amount.focus = False
        self.root.ids.input_home_country_amount.focus = False

        # currency exchange
        self.currency1 = self.root.ids.input_home_country_amount.text
        self.currency2 = self.root.ids.input_country_amount.text

        # spinner / home country name grabbing
        self.country1 = self.root.ids.home_country_label.text
        self.country2 = self.root.ids.country_selection.text

        # checks if spinner selection is blank
        if self.country2 is "":
            self.country2 = self.root.ids.country_selection.text = self.current_location

        # gets country details
        self.country_details1 = currency.get_details(self.country1)
        self.country_details2 = currency.get_details(self.country2)

        # checks to see if there was an inputted currency in the "home country" textbox, if there is no value, then it is assumed that the spinner country textbox has an inputted value.
        if self.currency1 is "":
            self.amount2 = currency.convert(self.currency2, self.country_details2[1], self.country_details1[1])
            print(self.amount2)
            self.amount2 = round(self.amount2, 3)
            if self.amount2 is -1:
                self.root.ids.input_country_amount.disabled = True
                self.root.ids.input_home_country_amount.disabled = True
            self.root.ids.input_home_country_amount.text = str(self.amount2)
            current_time = time.strftime("%H:%M:%S")
            self.root.ids.status.text = "updated at {}".format(current_time)

        # checks to see if there was an inputted currency in the spinner country textbox, if there is no value, then it is assumed that the "home country" textbox has an inputted value.
        elif self.currency2 is "":
            self.amount1 = currency.convert(self.currency1, self.country_details1[1], self.country_details2[1])
            self.amount1 = round(self.amount1, 3)
            print(self.amount1)
            if self.amount1 is -1:
                self.root.ids.input_country_amount.disabled = True
                self.root.ids.input_home_country_amount.disabled = True
            self.root.ids.input_country_amount.text = str(self.amount1)
            current_time = time.strftime("%H:%M:%S")
            self.root.ids.status.text = "updated at {}".format(current_time)
Esempio n. 15
0
    def test_not_update_cache(self, mock_get_cache_path, mock_timenow):
        """ test should not requests API if cache data less than 30 mins old """
        mock_get_cache_path.return_value = self.cache_path
        mock_timenow.return_value = 900  # 15 mins
        usd_aud_cache = currency.cache.read()['USD']['AUD']['value']

        self.assertEqual(currency.convert('USD', 'AUD'), usd_aud_cache)
Esempio n. 16
0
def show_converted_curr():
    """"show the converted currency"""

    convert_from = request.args.get("convert_from").upper()
    convert_to = request.args.get("convert_to").upper()
    amount = float(request.args.get("amount"))

    try:
        converted_amt = currency.convert(convert_from, convert_to, amount)
    except currency.exceptions.CurrencyException:
        convert_result = f"Conver From {convert_from} or Convert To{convert_to} is not valid currency, Please put in valid currencies"
        return jsonify(result=convert_result,
                       calculated=session[CALCULATED_KEY])

    formattet_convert_from = format_currency(amount, convert_from)
    formattet_convert_to = format_currency(converted_amt, convert_to)

    convert_result = f"{formattet_convert_from} is converted to {formattet_convert_to}"

    # save the calculated result to session
    calculated = session[CALCULATED_KEY]
    calculated.append(convert_result)
    session[CALCULATED_KEY] = calculated

    return jsonify(result=convert_result, calculated=session[CALCULATED_KEY])
Esempio n. 17
0
 def convert_to_home(
     self
 ):  # First of three conversion functions, to convert from the destination to the home currency.
     try:  # Tries this block of code first, but should a Value Error appear it will act out the except ValueError code
         country_details = (
             currency.get_all_details()
         )  # runs get_all_details in the currency.py file to obtain country codes in a dictionary
         amount = float(
             self.root.ids.input_location.text
         )  # Sets the current text as a float in the location/destination text field
         home_currency = self.root.ids.country_name.text  # obtains the country name from the GUI
         home_currency = country_details[home_currency]  # uses the name as a key on the already obtained dictionary
         home_currency_code = home_currency[1]  # Gets the country code from the result
         target_currency = (
             self.root.ids.spinner.text
         )  # Does the same as previous 3 lines, but for the target currency
         target_currency = country_details[target_currency]
         target_currency_code = target_currency[1]
         converted_number = currency.convert(
             amount, target_currency_code, home_currency_code
         )  # runs the convert function in currency.py
         self.status_update(
             target_currency[2].strip("\n"), target_currency_code, home_currency[2].strip("\n"), home_currency_code
         )  # Sets the status to show the conversion and the updated time
         self.root.ids.input_home.text = (
             converted_number
         )  # shows in the GUI text field that the currency was not entered what the conversion is
     except ValueError:  # Runs if a value error appears in the above code
         self.root.ids.input_home.text = "-1"  # this will be shown as the 'conversion' should a value error arise
         self.root.ids.status.text = "Error in Conversion"  # this is shown in the status.
Esempio n. 18
0
 def convert_to_home(
     self
 ):  #First of three conversion functions, to convert from the destination to the home currency.
     try:  #Tries this block of code first, but should a Value Error appear it will act out the except ValueError code
         country_details = currency.get_all_details(
         )  #runs get_all_details in the currency.py file to obtain country codes in a dictionary
         amount = float(
             self.root.ids.input_location.text
         )  #Sets the current text as a float in the location/destination text field
         home_currency = self.root.ids.country_name.text  #obtains the country name from the GUI
         home_currency = country_details[
             home_currency]  #uses the name as a key on the already obtained dictionary
         home_currency_code = home_currency[
             1]  #Gets the country code from the result
         target_currency = self.root.ids.spinner.text  #Does the same as previous 3 lines, but for the target currency
         target_currency = country_details[target_currency]
         target_currency_code = target_currency[1]
         converted_number = currency.convert(
             amount, target_currency_code,
             home_currency_code)  #runs the convert function in currency.py
         self.status_update(
             target_currency[2].strip('\n'), target_currency_code,
             home_currency[2].strip('\n'), home_currency_code
         )  #Sets the status to show the conversion and the updated time
         self.root.ids.input_home.text = converted_number  #shows in the GUI text field that the currency was not entered what the conversion is
     except ValueError:  #Runs if a value error appears in the above code
         self.root.ids.input_home.text = "-1"  #this will be shown as the 'conversion' should a value error arise
         self.root.ids.status.text = "Error in Conversion"  #this is shown in the status.
Esempio n. 19
0
def _currency_handler(args):
    if len(args) < 1:
        return strings.BAD_FORMAT

    from_match = re.match(r'^(?P<amount>\d+(?:(?:[.,])\d+)?)?(?P<currency>\w{3})$', args[0])
    if not from_match:
        return strings.BAD_FORMAT

    from_dict = from_match.groupdict()
    from_currency = from_dict.get('currency')

    if not is_supported(from_currency):
        return strings.BAD_CURRENCY_MESSAGE.format(currency=from_currency, api_provider_url=settings.API_PROVIDER_URL)

    match_amount = from_dict.get('amount')
    if not match_amount:
        amount = 1.0
    else:
        match_amount = float(match_amount.replace(',', '.'))
        if match_amount > settings.MINIMAL_AMOUNT:
            amount = match_amount
        else:
            return strings.BAD_AMOUNT_MESSAGE

    to_currencies = {}

    if len(args) == 1:
        if from_currency == settings.DEFAULT_CURRENCY:
            return strings.DEFAULT_CURRENCY_MESSAGE.format(default_currency=settings.DEFAULT_CURRENCY)
        to_currencies[settings.DEFAULT_CURRENCY] = convert(from_currency, settings.DEFAULT_CURRENCY, amount)
    else:
        for to_arg in args[1:]:
            to_match = re.match(r'^(?P<currency>\w{3})$', to_arg)
            if not to_match:
                continue
            to_currency = to_match.groupdict().get('currency')
            if not is_supported(to_currency):
                return strings.BAD_CURRENCY_MESSAGE.format(currency=to_currency,
                                                           api_provider_url=settings.API_PROVIDER_URL)
            to_currencies[to_currency] = convert(from_currency, to_currency, amount)
        if not to_currencies:
            return strings.BAD_FORMAT

    return {'from_currency': from_currency, 'to_currencies': to_currencies, 'amount': amount}
Esempio n. 20
0
def convert_currency():
    if request.method == 'POST':
        amount = float(request.form['amount'])
        c_from = str(request.form.get('c_from'))
        c_to = str(request.form.get('c_to'))
        c_amount = convert(c_from, c_to, amount)

        show = False

        return render_template('response.html', show=show, amount=amount, c_from=c_from, c_to=c_to, c_amount=c_amount)

    return render_template('currency_form.html')
Esempio n. 21
0
File: app.py Progetto: cfitz25/Kivy
 def currency_update(self):
     # check if app disabled
     if (self.app_can_run == True):
         # get home_code and and country_code using the dictionary
         for i in self.current_trip.location:
             home_code = self.Destinations[self.home_country]
             destination_code = self.Destinations[i[0]]
             # send codes to currency.convert() and then add that value to the currency_rates list
             currency_rate = currency.convert(home_code[1], destination_code[1])
             self.currency_rates.append(currency_rate)
         # run conversion using on_enter_home()
         self.on_enter_home()
         # update last updated time in status window
         self.root.ids.status_window.text = "Updated at " + datetime.datetime.now().strftime("%H:%M:%S")
Esempio n. 22
0
 def get_currency_conversion(self, directions):
     # print(directions)
     # creates a dictionary from the currency module
     place_dictionary = get_all_details()
     # stores the user selection from the spinner gui
     spinner_location = self.root.ids.country_selection.text
     # print(spinner_location)
     location_currency = place_dictionary[spinner_location][1]
     home_currency = place_dictionary[self.home_country][1]
     # print(location_currency)
     # print(home_currency)
     # provides the status message and conversion amount in the gui
     # allows for back and forth conversion
     if directions == 'to home':
         value = convert(float(self.root.ids.target_amount.text),
                         home_currency, location_currency)
         self.root.ids.home_amount.text = str(value)
         self.root.ids.status.text = location_currency + ' to ' + home_currency
     else:
         value = convert(float(self.root.ids.home_amount.text),
                         location_currency, home_currency)
         self.root.ids.target_amount.text = str(value)
         self.root.ids.status.text = home_currency + ' to ' + location_currency
Esempio n. 23
0
 def do_POST(self):
     content_length = int(self.headers['Content-Length'])
     (input1,
      input2) = self.rfile.read(content_length).decode('utf-8').split('&')
     (a, amount) = input1.split('=')
     (b, cur) = input2.split('=')
     value = urllib.parse.unquote_plus(value)
     self.send_response(200)
     self.wfile.write(
         b'<head><style>p, button {font-size: 1em}</style></head>')
     self.wfile.write(b'<body>')
     self.wfile.write(b'<p>' +
                      bytes(currency.convert(int(amount), cur), 'utf-8') +
                      b'</p>')
     self.wfile.write(b'</body>')
Esempio n. 24
0
 def converter_back(self):
     result = currency.convert(
         self.root.ids.second_input.text,
         self.dict[self.root.ids.home_country.text][1],
         self.dict[self.root.ids.choose_currency.text][1])
     if result == -1:
         self.root.ids.first_input.disabled = True
         self.root.ids.second_input.disabled = True
     else:
         self.root.ids.first_input.text = str(result)
         self.root.ids.status_app.text = "{}({}) to {}({})".format(
             self.dict[self.root.ids.home_country.text][1],
             self.dict[self.root.ids.home_country.text][2],
             self.dict[self.root.ids.choose_currency.text][1],
             self.dict[self.root.ids.choose_currency.text][2])
Esempio n. 25
0
def display_results():
    currency1 = request.args.get('currency1')
    currency2 = request.args.get('currency2')
    amount = request.args.get('amount')
    new_amount = convert(currency1, currency2, amount)
    if type(new_amount) is dict:
        validity = new_amount
        session['invalid'] = [validity, currency1, currency2, amount]
        return redirect('/')

    return render_template('results.html',
                           c1=symbol(currency1),
                           c2=symbol(currency2),
                           amount=amount,
                           new_amount=new_amount)
Esempio n. 26
0
 def convert(
         self
 ):  #conversion upon getting a selected country name from spinner
     self.converted_amount = currency.convert(
         1, self.home_country_details[1], self.selected_country_details[1]
     )  #a. converts the amount using convert() from currency module
     self.root.ids.input_selected.text = str(
         ("{:.3f}".format(self.converted_amount))
     )  #b. allowing only 3 significant decimal digits as per the requirement
     self.root.ids.input_home.text = str(
         1)  #default conversation rate of home country (= 1)
     self.root.ids.status_bar.text = str("{} ({}) to {} ({})".format(
         self.home_country_details[1], self.home_country_details[2],
         self.selected_country_details[1],
         self.selected_country_details[2]))  #c. updates the status bar
Esempio n. 27
0
    def test_convert(self, mock_get_cache_path, _):
        """ test converting between currencies """
        mock_get_cache_path.return_value = '/tmp/test_cache_write'

        self.assertEqual(currency.convert('USD', 'PHP'), 46.211)
        self.assertEqual(currency.convert('EUR', 'JPY'), 133.2801)
        self.assertEqual(currency.convert('GBP', 'DKK'), 8.377764)

        self.assertEqual(currency.convert('USD', 'PHP', 2), 92.422)
        self.assertEqual(currency.convert('EUR', 'JPY', 10), 1332.801)
        self.assertEqual(currency.convert('GBP', 'DKK', 0), 0)
    def convert_to_home(self, target_amount, home_country, target_country):
        # dont know how to reciece the inputed amount and put it in the the function

        code1 = target_country
        amount = target_amount
        code2 = home_country
        target_amount = ''
        conversion = convert(amount, code1, code2)

        # get selected country = ''
        # get the inputed amount from target_amount
        # get selected countries code
        # get home countries code
        # put the amount and codes back into convert function
        # output result in home_amount (kivy)
        # update Satus (USD to AUD)
        pass
    def convert_to_home(self, target_amount, home_country, target_country):
        # dont know how to reciece the inputed amount and put it in the the function

        code1 = target_country
        amount = target_amount
        code2 = home_country
        target_amount = ''
        conversion = convert(amount, code1, code2)

        # get selected country = ''
        # get the inputed amount from target_amount
        # get selected countries code
        # get home countries code
        # put the amount and codes back into convert function
        # output result in home_amount (kivy)
        # update Satus (USD to AUD)
        pass
Esempio n. 30
0
 def calc(self):
     for name, cmd in self.tariff.get_formula().items():
         try:
             ok = self._interpret(cmd['condition'])
         except (tariff.TariffException, KeyError):
             ok = False
         if name == 'default' or ok:
             minimum = decimal.Decimal(
                 currency.convert('EUR', self._value('currency'),
                                  self._value('minimum_EUR')))
             cost = self._interpret(cmd['cost'])
             res = max(minimum, cost)
             res = res.quantize(decimal.Decimal('1'),
                                rounding=decimal.ROUND_HALF_DOWN)
             return {'cost': int(res), 'currency': self._value('currency')}
     raise tariff.TariffException(
         'Your request is not satisfy any condition')
Esempio n. 31
0
 def convert_to_location(self):  # Same as previous function except inversed
     try:
         country_details = currency.get_all_details()
         amount = float(self.root.ids.input_home.text)
         home_currency = self.root.ids.country_name.text
         home_currency = country_details[home_currency]
         home_currency_code = home_currency[1]
         target_currency = self.root.ids.spinner.text
         target_currency = country_details[target_currency]
         target_currency_code = target_currency[1]
         converted_number = currency.convert(amount, home_currency_code, target_currency_code)
         self.root.ids.input_location.text = converted_number
         self.status_update(
             home_currency[2].strip("\n"), home_currency_code, target_currency[2].strip("\n"), target_currency_code
         )
     except ValueError:
         self.root.ids.input_location.text = "-1"
         self.root.ids.status.text = "Error in Conversion"
Esempio n. 32
0
 def convert_selected_to_home(
     self
 ):  #conversion upon getting an amount at selected country textinput
     try:
         self.converted_amount_st = currency.convert(
             self.root.ids.input_selected.text,
             self.selected_country_details[1],
             self.home_country_details[1])  #a.
         self.root.ids.input_home.text = str(
             ("{:.3f}".format(self.converted_amount_st)))  #b.
         self.root.ids.status_bar.text = str("{} ({}) to {} ({})".format(
             self.selected_country_details[1],
             self.selected_country_details[2], self.home_country_details[1],
             self.home_country_details[2]))  #c.
     except:
         print(
             "ERROR IN CONVERSION."
         )  #prints error in the program but continues as it's in try and except
Esempio n. 33
0
 def load_data(self):
     # load date and store in label, set last updated time
     self.root.ids.lbl_date.text = "Today is: " + time.strftime("%Y/%m/%d")
     self.root.ids.lbl_status.text = "Last updated: " + time.strftime("%H:%M:%S") + "\n" + time.strftime("%Y/%m/%d")
     # start conversion, store rate, Enable Textinput, if something goes wrong they will be disabled
     self.root.ids.txt_foreign_amount.disabled = False
     self.root.ids.txt_home_amount.disabled = False
     self.home_currency = get_details(self.root.ids.lbl_home_country.text)
     self.target_currency = get_details(self.root.ids.country_spinner.text)
     if self.root.ids.country_spinner.text != "":
         try:
             self.rate = convert(1, self.home_currency[1], self.target_currency[1])
         except:
             self.root.ids.lbl_error.text = "Error: Null Rate"
             self.root.ids.txt_foreign_amount.disabled = True
             self.root.ids.txt_home_amount.disabled = True
     else:
         self.root.ids.country_spinner.text = self.current_country
Esempio n. 34
0
	def data(self, username=None):
		print "data| username="******"SELECT id, default_currency FROM USERS WHERE username=?"
		res = cursor.execute(query, (username, ))
		row = res.fetchone()
		user_id = row[0]
		default_currency = row[1]
		query = "SELECT date, amount, currency, given_by, why, notes, id FROM MONEY WHERE user_id=? ORDER BY date ASC"
		res = cursor.execute(query, (user_id, ))
		data = []
		for row in res.fetchall():
			r = {	'date': int(row[0]),
					'amount': int(row[1]),
					'amount_in_default_currency': 0,
					'currency': row[2],
					'given_by': row[3],
					'why': row[4],
					'notes': row[5],
					'id': row[6]}
			# convert amount to default currency
			m = convert(r['amount'], r['currency'], default_currency)
			if m != 'nocon' and m != 'nonvalidcurrency':
				r['amount_in_default_currency'] = m
			else:
				r['amount_in_default_currency'] = amount
				
			data.append(r)
		con.close()
		return demjson.encode({'error_code': 1,'data': data, 'default_currency': default_currency})
Esempio n. 35
0
def process_crypto_info(crypto):
    """ convert to local currency if specified in config file
	trim long decimals and format price number. then save into cache file """

    base_currency = config['global']['base_currency'].lower()
    local_price_str = 'price_' + base_currency

    price_btc = float(crypto['price_btc'])
    price_usd = currency.rounding(crypto['price_usd'], 'USD')
    if local_price_str not in crypto:  # API failed to convert to local price
        price = currency.convert('USD', base_currency, price_usd)
        local_price = currency.rounding(price, local_price_str)
    else:
        local_price = currency.rounding(crypto[local_price_str], base_currency)
    # dont have bitcoin icon yet :(
    crypto['price_btc'] = currency.pretty(price_btc, 'BTC', abbrev=False)
    crypto['price_usd'] = currency.pretty(price_usd, 'USD')
    crypto[local_price_str] = currency.pretty(local_price, base_currency)
    return crypto
Esempio n. 36
0
 def convert_to_location(self):  #Same as previous function except inversed
     try:
         country_details = currency.get_all_details()
         amount = float(self.root.ids.input_home.text)
         home_currency = self.root.ids.country_name.text
         home_currency = country_details[home_currency]
         home_currency_code = home_currency[1]
         target_currency = self.root.ids.spinner.text
         target_currency = country_details[target_currency]
         target_currency_code = target_currency[1]
         converted_number = currency.convert(amount, home_currency_code,
                                             target_currency_code)
         self.root.ids.input_location.text = converted_number
         self.status_update(home_currency[2].strip('\n'),
                            home_currency_code,
                            target_currency[2].strip('\n'),
                            target_currency_code)
     except ValueError:
         self.root.ids.input_location.text = "-1"
         self.root.ids.status.text = "Error in Conversion"
Esempio n. 37
0
 def conversion_rates(
     self
 ):  # Same as the first conversion function, however always defaults to only converting 1 in the selected currency for the conversion rate rather than an actual conversion
     try:
         country_details = currency.get_all_details()
         amount = float("1")
         home_currency = self.root.ids.country_name.text
         home_currency = country_details[home_currency]
         home_currency_code = home_currency[1]
         target_currency = self.root.ids.spinner.text
         target_currency = country_details[target_currency]
         target_currency_code = target_currency[1]
         converted_number = currency.convert(amount, target_currency_code, home_currency_code)
         self.status_update(
             target_currency[2].strip("\n"), target_currency_code, home_currency[2].strip("\n"), home_currency_code
         )
         self.root.ids.input_home.text = converted_number
         self.root.ids.input_location.text = "1"
     except ValueError:
         self.root.ids.input_home.text = "-1"
         self.root.ids.status.text = "Error in Conversion"
Esempio n. 38
0
 def conversion_rates(
     self
 ):  #Same as the first conversion function, however always defaults to only converting 1 in the selected currency for the conversion rate rather than an actual conversion
     try:
         country_details = currency.get_all_details()
         amount = float("1")
         home_currency = self.root.ids.country_name.text
         home_currency = country_details[home_currency]
         home_currency_code = home_currency[1]
         target_currency = self.root.ids.spinner.text
         target_currency = country_details[target_currency]
         target_currency_code = target_currency[1]
         converted_number = currency.convert(amount, target_currency_code,
                                             home_currency_code)
         self.status_update(target_currency[2].strip('\n'),
                            target_currency_code,
                            home_currency[2].strip('\n'),
                            home_currency_code)
         self.root.ids.input_home.text = converted_number
         self.root.ids.input_location.text = "1"
     except ValueError:
         self.root.ids.input_home.text = "-1"
         self.root.ids.status.text = "Error in Conversion"
 def update_rate(self, key):
     """ When country is changed/button pressed, update currency """
     # If activated by button (key=True) spinner is blank, set spinner to current country
     if self.root.ids.country_spinner.text == "" and key:
         self.root.ids.country_spinner.text = self.current_country
     self.travel_country = self.root.ids.country_spinner.text
     self.get_country_details()
     # Retrieve country/trip details
     # If currency is the same and function activated by spinner, don't update
     # If lists are still empty, don't update
     if (key or self.update_indicator) and self.travel_details and self.home_details:
         # Update conversion rate
         self.conversion_rate = convert(1, self.home_details[1], self.travel_details[1])
         # Error checking, enable input if conversion success
         if self.conversion_rate == -1:
             self.root.ids.status_label.text = "Update Failed"
             self.toggle_inputs_disabled(True)
         else:
             self.clear_inputs()
             self.toggle_inputs_disabled(False)
             self.root.ids.status_label.text = "Updated at: " + time.strftime("%I:%M:%S%p")
     # Reset indicators
     self.update_indicator = True
 def test_convert(self):
     self.assertEqual(convert('USD', 'USD', 100), 100)
     self.assertIsNotNone(convert('USD', 'EUR', 100))
     self.assertEquals(convert('USD', 'NOTVALID', 100), {
         'c1': True,
         'c2': False,
         'amount': True
     })
     self.assertEquals(convert('NOTVALID', 'NOTVALID', 100), {
         'c1': False,
         'c2': False,
         'amount': True
     })
     self.assertEquals(convert('USD', 'URO', ''), {
         'c1': True,
         'c2': False,
         'amount': False
     })
     self.assertEquals(convert('USD', 'URO', None), {
         'c1': True,
         'c2': False,
         'amount': False
     })
Esempio n. 41
0
import requests
from decimal import Decimal
from currency import convert

correct = Decimal('3754.8057')
result = convert(Decimal('1000.1000'), 'RUR', 'JPY', "17/02/2005")
if result == correct:
    print("Correct")
else:
    print("Incorrect: %s != %s" % (result, correct))
 def get_conversion_rate(self):
     self.forward_conversion_rate = convert(1, self.home_currency, self.target_currency)
     self.backward_conversion_rate = convert(1, self.target_currency, self.home_currency)
 def get_currency_conversion(self):
     self.conversion_factor = float(currency.convert(1, self.home_country_tuple[1], self.from_country_tuple[1]))
     self.reverse_conversion_factor = float(currency.convert(1, self.from_country_tuple[1], self.home_country_tuple[1]))
     print(self.conversion_factor)
Esempio n. 44
0
__author__ = 'connor'
import web_utility
import currency

amount = input("Amount: ")
currentC = input("Current: ")
travelC = input("Travel: ")
currentCountry = currency.get_details(currentC)
travelCountry = currency.get_details(travelC)
result = currency.convert(amount, currentCountry[1], travelCountry[1])

print(result)
Esempio n. 45
0
__author__ = 'connor'
import trip
import currency

add = True
trips = trip.Details()

while add == True:
    if trips.isEmpty() == True:
        first = "first"
    else:
        first = "next"
    country = input("Type country to travel too " + first + ""
                                                            ": ")
    start_date = input("Type the date you wish to go to the country. eg, 30 12 15: ")
    end_date = input("Type the date you wish to return. eg, 31 12 15: ")

    trips.add(country, start_date, end_date)
    if input("Would you like to add another trip? Y or N: ") == "Y":
        add = True
    else:
        add = False

currentCountry = currency.get_details(input("Type current country: "))
tripCountry = currency.get_details(trips.current_country(input("Add Current Date. eg, 31 12 15: ")))
currentCountryInfo = trip.Country(currentCountry[0], currentCountry[1], currentCountry[2])
tripCountryInfo = trip.Country(tripCountry[0], tripCountry[1], tripCountry[2])
result = currency.convert(input("Type the amount you wish to convert: "), currentCountry[1], tripCountry[1])
output = tripCountryInfo.Currency(result)
print(output)