def delete_currency(symbol):
    if request.method == "DELETE":
        c = Currency()
        if c.delete(symbol.upper()):
            return jsonify(
                {"message": symbol.upper() + " removed successfully"}), 200

    return jsonify({"error": "Unable to delete currency"}), 404
 def test_get_specified_related_currency(self):
     dictionary = \
         [CurrencyNameValuePair("euro", 2),
          CurrencyNameValuePair("dollar", 3)]
     currency = Currency("", dictionary)
     self.assertEqual \
         (3,
          currency.get_related_currency_by_name("dollar")
          .get_value())
def add_currency():
    if request.method == "POST":
        c = Currency()
        symbol = request.get_json()['symbol'].upper()

        response_message, response_status = c.create({'symbol': symbol})
        if response_status == 201:
            return jsonify({"message": response_message}), response_status
        else:
            return jsonify({"error": response_message}), response_status
Esempio n. 4
0
def getFromApiAndCommit():
    rates = []
    url = baseUrl.format(time, accessKey)
    try:
        response = requests.get(url)
        if response.status_code == 200:
            json = response.json()
            ratesKvp = json["rates"]
            date = json["date"]
            for rate in ratesKvp:
                r = Currency(name=rate, rate=ratesKvp[rate], date=date)
                rates.append(r)
                db.session.add(r)
            db.session.commit()
        else:
            print("Failed to get rates, {}".format(response.status_code))
            raise CurrencyError("Failed to get rates from API, {}".format(
                response.status_code))
    except Exception as e:
        db.session.rollback()
        db.session.flush()
        print(str(e))
        raise CurrencyError(str(e))

    return rates
Esempio n. 5
0
    def populate_db():
        print("Trying to populate Database")
        c = Currency()

        c.create({"symbol": "BRL"})
        c.create({"symbol": "BTC"})
        c.create({"symbol": "USD"})
        c.create({"symbol": "ETH"})
        c.create({"symbol": "EUR"})
def initCustomerData():
    customers = []
    customerA = Customer(
        1, 'John K', '123456', '54634636', '1234',
        Account(1, '23456', Currency(1, 'KES', 'Kenya Shillings', 'Kshs'),
                10000))
    customers.append(customerA)
    customerB = Customer(
        1, 'Brian O', '98765', '363463', '7689',
        Account(2, '9845673', Currency(1, 'KES', 'Kenya Shillings', 'Kshs'),
                5000))
    customers.append(customerB)
    customerC = Customer(
        1, 'Ann M', '353534', '3463636', '4567',
        Account(3, '98965757', Currency(1, 'KES', 'Kenya Shillings', 'Kshs'),
                3000))
    customers.append(customerC)
    bankCustomers = Customers(customers)
    return bankCustomers
Esempio n. 7
0
def send_request(date):
    """ Function to send request to server save last date of request in txt file, save currency in db
    :param date
    :return list of currency
    """
    # making request tos server
    response = requests.get(
        'https://api.exchangeratesapi.io/latest?base=USD').json()
    result = response['rates']
    list_currency = []
    # save all currency in db, send response to user with all currency
    for currency in result:
        value = round(result[currency], 2)
        item = '{}: {}'.format(currency, value)
        list_currency.append(item)
    # save date of request in txt file
    with open('date.txt', 'wt') as file:
        file.write(str(date)[:19])
    # save all currency in db
    Currency.add_currency(list_currency)
    return list_currency
    def deserialize(currency_data_xml: str) -> Currency:
        rates = []
        tree = ET.fromstring(currency_data_xml)
        name = tree.get('name')
        rates_tags = tree.getiterator('rate')
        for rate_tag in rates_tags:
            rates.append(
                Rate(
                    datetime.strptime(rate_tag.find('date').text,
                                      '%d/%m/%Y').date(),
                    float(rate_tag.find('value').text)))

        return Currency(name, rates)
def restore_currencies_data(from_date: datetime, currency_name: str):
    currency_rate_data_provider = CurrencyRateDataProvider()
    intermediate_repository = S3IntermediateRepository()
    persistence_repository = PersistenceRepository()

    to_date = datetime.today()

    rates = currency_rate_data_provider.get_currency_rates(
        from_date, to_date, currency_name)
    intermediate_repository.store_currency_data(Currency(currency_name, rates))
    currency = intermediate_repository.get_currency_data(currency_name)
    if currency is not None:
        persistence_repository.store_non_unique_currency_data(currency)
        intermediate_repository.delete_currency_data(currency_name)
def fetch_new_currencies_data():
    currency_rate_data_provider = CurrencyRateDataProvider()
    intermediate_repository = S3IntermediateRepository()
    persistence_repository = PersistenceRepository()

    days_to_fetch = Settings.DEFAULT_DAYS_TO_FETCH
    default_from_date = datetime.today() - timedelta(days=days_to_fetch)
    to_date = datetime.today()

    for currency_name in Settings.CURRENCIES:
        from_date = persistence_repository.get_last_stored_currency_rate_date(
            currency_name)
        if from_date is None:
            from_date = default_from_date
        else:
            from_date = from_date + timedelta(days=1)
        rates = currency_rate_data_provider.get_currency_rates(
            from_date, to_date, currency_name)
        currency = Currency(currency_name, rates)
        intermediate_repository.store_currency_data(currency)
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
Esempio n. 12
0
def currency_scraper(symbol):
    try:

        symbol = symbol + Currency.X
        url = PAGE_FINANCE_YAHOO + '/quote/%s' % symbol

        html = urlopen(url)
        bsObj = BeautifulSoup(html.read().decode('utf-8', 'ignore'),
                              "html.parser")

        value_symbol = bsObj.find('div', {
            'id': 'quote-market-notice'
        }).parent.parent.find_next('span').text

        cast_currency = Currency(symbol_text=symbol,
                                 current_value=value_symbol)

        return cast_currency.__dict__

    except:
        return {}
Esempio n. 13
0
def currencies_scraper():

    try:

        url = PAGE_FINANCE_YAHOO + '/currencies'

        html = urlopen(url)
        bsObj = BeautifulSoup(html.read().decode('utf-8', 'ignore'),
                              "html.parser")

        data = []

        symbols = bsObj.find_all('a', {'class': 'Fw(b)'})

        for symbol in symbols:
            cast_currency = Currency(symbol.text, symbol.get('title'))
            data.append(cast_currency.__dict__)

        return data

    except:
        return []
Esempio n. 14
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 test_get_absent_related_currency(self):
     dictionary = \
         [CurrencyNameValuePair("euro", 2),
          CurrencyNameValuePair("dollar", 3)]
     currency = Currency("", dictionary)
     self.assertEqual(None, currency.get_related_currency_by_name("rororo"))
Esempio n. 16
0
async def handle(msg):
    """ Function to handle user input
    Take user massage and return response
    """
    command = msg['text']
    # get datetime of massage
    date = datetime.now()
    # function from helper to check when was last request
    check_request = check_last_request(date)
    if command == '/list' or command == '/lst':
        # if last request more than 10 mn ago
        if check_request:
            # make request to server for all currency
            result = send_request(date)
            massage = '\n'.join(result)
            await bot.sendMessage(msg['from']['id'], massage)
        else:
            # if last request les then 10 mn. ago
            print('from db')
            # get all currency from db
            result = Currency.get_all()
            # send response to user
            massage = '\n'.join(result)
            await bot.sendMessage(msg['from']['id'], massage)
    elif command[:9] == '/exchange':
        # get currency from user massage
        currency = command[len(command)-3:]
        # get amount of currency what user want to change
        amount_str = re.findall(r'([0-9]+)', command)
        print(amount_str)
        # check if user use valid command
        if len(amount_str) == 0 or currency.isupper() != True:
            await bot.sendMessage(msg['from']['id'], "Please use valid command!\nExample:\n/exchange $10 to CAD")
        # convert amount to float
        amount = float(amount_str[0])
        # if request made more than 10 mn. ago
        if check_request:
            # send request to server
            result = send_request(date)
            print(result)
            # round currency
            # rate = round(result[currency], 2)
            item = [r for r in result if currency in r]
            rate = item[0][5:]
            exchanged = float(rate) * amount
            await bot.sendMessage(msg['from']['id'], '${}'.format(exchanged))
        else:
            # if request les then 10 mn, make request to db
            result = Currency.get_all()
            # search for currency in least
            item = [r for r in result if currency in r]
            rate = item[0][5:]
            exchanged = float(rate) * amount
            await bot.sendMessage(msg['from']['id'], '${}'.format(exchanged))
    elif command[:8] == '/history':
        # get all date from command for request
        # get base and symbol from command
        base_symbols = re.findall(r'\w{3}/\w{3}', command)
        # get base
        base = base_symbols[0][:3]
        # get symbol
        symbols = base_symbols[0][4:]
        # calculate start_at date
        start_at_datetime = date - timedelta(days=6)
        # convert start_at date to string
        start_at = datetime.strftime(start_at_datetime, "%Y-%m-%d")
        # convert end date (today) to string
        end_at = datetime.strftime(date, "%Y-%m-%d")
        response = requests.get('https://api.exchangeratesapi.io/history?start_at={}&end_at={}&base={}&symbols={}'.format(start_at, end_at, base, symbols)).json()
        # if not get response return massage
        if len(response['rates']) == 0:
            await bot.sendMessage(msg['from']['id'], 'No exchange rate data is available for the selected currency')
        else:
            # call create graph function from helper
            graph = create_graph(response['rates'], symbols)
            if graph:
                # send graph
                with open(graph, 'rb') as g:
                    await bot.sendPhoto(msg['from']['id'], (graph, g))
                os.remove(graph)
            else:
                await bot.sendMessage(msg['from']['id'], 'Something go wrong please try again later')
    # if user add any unrecognized command send list of commands
    else:
        massage = "Dear user please choose one from next commands:\n/list\nto get list of all currency\n/exchange " \
                  "$10 to CAD or /exchange 10 USD to CAD\nto exchange some currency\n/history USD/CAD for 7 days\n" \
                  "to get history of some currency for last 7 days"
        await bot.sendMessage(msg['from']['id'], massage)
def get_tasks():
    c = Currency()
    return jsonify(c.find({})), 200
 def test_get_name2(self):
     self.assertNotEqual("somethingElse", Currency("wojtek", []).get_name())
Esempio n. 19
0
 def get_currency(self, _currency_name) -> Currency:
     currency_rates_data = session.query(CurrencyRate).filter_by(
         currency=_currency_name)
     rates = map(lambda c: Rate(c.date, c.rate), currency_rates_data)
     return Currency(_currency_name, rates)
Esempio n. 20
0
from models.account import Account
from models.customer import Customer
from models.customers import Customers
from models.currency import Currency

customers = []

customerA= Customer(1,'John K','123456','35353','1234',Account(1,'23456',Currency(1,'KES','Kenya Shillings','Kshs'),10000))
customers.append(customerA)

customerB = Customer(1,'Brian O','98765','353535','7689',Account(2,'9845673',Currency(1,'KES','Kenya Shillings','Kshs'),5000))
customers.append(customerB)

customerC = Customer(1,'Ann M','353534','532225','4567',Account(3,'98965757',Currency(1,'KES','Kenya Shillings','Kshs'),3000))
customers.append(customerC)

bankCustomers= Customers(customers)


print('\n\n** Welcome to The Codevillage Bank **\n')

print('1 Check Balance \n\n')

print('2 Send Money \n\n')

print('3 Press any key to Exit \n\n')

userOption = int(input(' Select a menu to proceed \n\n'))

if userOption == 1:
    phoneNo = input('Enter phone number \n')
 def test_currency_with_null_name(self):
     self.assertNotEqual("", Currency(None, []).get_name())
 def test_get_currencyVector(self):
     dictionary = [CurrencyNameValuePair("euro", 2), CurrencyNameValuePair("dollar", 3)]
     currency = Currency("", dictionary)
     self.assertEqual \
         (dictionary, currency.get_all_related_currencies_as_list())
 def test_currency_with_name_zero_length(self):
     self.assertEqual("", Currency("", []).get_name())
 def test_get_name(self):
     self.assertEqual("wojtek", Currency("wojtek", []).get_name())
def get_all_currencies(symbol):
    c = Currency()
    return c.find_by_symbol(symbol), 200