def setUp(self): self.app = create_app('default') self.app_context = self.app.app_context() self.app_context.push() db.create_all() Bank.generate_fake() self.client = self.app.test_client(use_cookies=True)
def get_rates(self): """Gets latest rates from target resource and stores in maps.""" self.log.info('number of requests: %s' % self.number_of_requests) self.log.info('opening URL %s' % URL_EN) self.__g.go(URL_EN) self.log.info('done') self.banks = {} self.rates = {} # acquiring current time now = datetime.now() # parsing response HTML for table_row in self.__g.doc.select('//table[@id="rb"]/tr'): try: # acquiring bank logo img_selector_list = table_row.select('.//td[@class="bank"]/img/@src').one() bank_logo_uri = img_selector_list.text() # acquiring bank name in English bank_html_name = table_row.select('.//td[@class="bank"]/a').text() bank_name_en = re.sub('[.]', '', bank_html_name).strip() # initializing bank and rate objects from models import Bank, Rate bank = Bank(bank_logo_uri, now) bank.name_en = bank_name_en rate = Rate(now) # acquiring currency rates column = 1 for td in table_row.select('.//td'): if column == 5: time_str = str(now.year) + ' ' + td.text() update_time = datetime.strptime(time_str, FMT_DATE_TIME_PATTERN_RATE_AM) rate.declared_update_time = update_time if column == 6: rate.usd_buying = td.text() if column == 7: rate.usd_selling = td.text() if column == 8: rate.eur_buying = td.text() if column == 9: rate.eur_selling = td.text() if column > 9: break column += 1 # adding bank and rates to containers self.banks[bank_logo_uri] = bank self.rates[bank_logo_uri] = rate except DataNotFound: pass # Rows passed through filter, that do not contain valuable data except UnicodeEncodeError, err: self.log.error(str(err))
def deploy(): """Run deployment tasks.""" from flask_migrate import upgrade from models import Bank # migrate database to latest revision upgrade() # create user roles db.create_all() Bank.generate_fake()
def __init__(self, bank_name='', bank=None): self.bank = bank or Bank.get(name=bank_name.title()) if self.bank is None: raise ValueError('Bank not supported.') # Defining each bank parsing method if self.bank.name == 'Tangerine': """ Tangerine CSV format: Transaction date,Transaction,Name,Memo,Amount """ # 0-Date, 2-Description, 4-Amount self.description = lambda row: row[2] self.amount = lambda row: float(row[4] or '0') self.date = lambda row: self.format_date(row[0], '%m/%d/%Y') self.start_at = 1 self.columns = 5 elif self.bank.name == 'Desjardins': """ Desjardins CSV format: https://www.desjardins.com/en/services_en_ligne/accesd_affaires/soutien/guiderel.pdf """ # 3-Date, 5-Description, 6-Cheque #, 7-Withdrawal, 8-Deposit self.description = lambda row: row[5] + (' #' + row[6] if row[6] else '') self.amount = lambda row: float(row[8] or '0') or -float(row[7] or '0') self.date = lambda row: self.format_date(row[3], '%Y/%m/%d') self.start_at = 0 self.columns = 14 else: raise ValueError('Bank not supported yet.')
def addBank(): params = [ 'name', 'locality', 'city', 'ifsc_code', 'start_time', 'end_time', 'password', 'username' ] for param in params: if request.form.get(param) is None: return Response(param + ' field is required', status=400) bank = Bank.query.filter_by(ifsc_code=request.form['ifsc_code']).first() if bank is not None: return Response('Bank with the same ifsc code already exists', status=400) bank = Bank.query.filter_by(username=request.form['username']).first() if bank is not None: return Response('Bank with the same username already exists', status=400) bank = Bank(name=request.form['name'], locality=request.form['locality'], city=request.form['city'], start_time=request.form['start_time'], end_time=request.form['end_time'], ifsc_code=request.form['ifsc_code'], password=request.form['password'], username=request.form['username']) session = db_session() session.add(bank) session.commit() bank_json = as_dict(bank) return Response(json.dumps(bank_json), status=200)
def create_new_banks(): """ Create a new bank information **Example request**: .. sourcecode:: http POST /bank city= name= address= Host: localhost Accept: application/json """ city = request.form.get('bankCity', '') name = request.form.get('bankName', '') address = request.form.get('bankAddress', '') info = dict(city=city, name=name, address=address) # print(info) bank = Bank(city, name, address) res = bank.save() # print('res=%d' % res) return send_result(info, res, status="True")
def settlement_ep(): sig = request.headers.get("X-Signature") content = request.json api_key = content["api_key"] nonce = content["nonce"] bank = content["bank"] amount = content["amount"] res, reason, api_key = check_auth(api_key, nonce, sig, request.data) if not res: return bad_request(reason) bank = Bank.from_token(db.session, bank) if not bank or bank.user != api_key.user: return bad_request("invalid bank account") amount_receive = _settlement_calc(api_key, amount) if amount_receive <= 0: return bad_request("Settlement amount less then or equal to 0") count_this_month = Settlement.count_this_month(db.session, api_key.user) max_this_month = api_key.user.max_settlements_per_month if api_key.user.max_settlements_per_month else 1 if count_this_month >= max_this_month: return bad_request("Settlement count max reached for this month") settlement = Settlement(api_key.user, bank, amount, app.config["SETTLEMENT_ADDRESS"], amount_receive) db.session.add(settlement) db.session.commit() return jsonify(settlement.to_json())
def get_data_db(): data = [{ 'name': bank.name, 'buy': bank.buy, 'sell': bank.sells } for bank in Bank.select()] return data
def __init__(self, num_players, board=Board(DEFAULT_TILES), cards=Cards()): self.num_players = num_players self.players = {} self.board = board self.bank = Bank(board, self.players) self.cards = cards self.turns = 0
def add_bank(*args): add = Bank( bank_name=args[0], checkings_total=args[1], savings_total=args[2], ) session.add(add) session.commit()
def put(self): """API Endpoint for creating new bank """ args = _bank_parser.parse_args() bank = Bank(name=args['name']) db.session.add(bank) db.session.commit() return json_serialize(bank)
def failed_bank_detail(cert_num): """ This route is for a single bank. We're going to do TWO things. a.) We're going to get the one bank. b.) We're going to get all banks EXCEPT this bank in the same state. """ # a.) Get this bank. this_bank = Bank.select().where(Bank.cert_num == int(cert_num)).get() # b.) Get the other banks in this state. same_state_banks = Bank.select().where(Bank.state == this_bank.state).where(Bank.cert_num != int(cert_num)) # Set up the context; include both this bank and other banks from this state. context = {"bank": this_bank, "same_state_banks": same_state_banks} # Render the template to detail.html and with that context. return render_template("detail.html", **context)
def parse_website(): site = 'https://ftime.by/kursy-valyut/minsk' hdr = {'User-Agent': 'Mozilla/5.0'} req = Request(site, headers=hdr) page = urlopen(req) soup = BeautifulSoup(page, "html.parser") for d in soup.find_all('tbody'): for c in d.find_all('tr'): try: bank = c.find('a').string bank_buys = c.find('div', 'field-kurs-pokupka-usd').string[5:9] bank_selling = c.find('div', 'field-kurs-sale-usd').string[5:9] except Exception as e: print('***ERROR parser.py - ', e) continue Bank.create(name=bank, buy=bank_buys, sells=bank_selling)
def save(self, property_id, commit=True): property = Property.objects.get(id=property_id) if 'add_bank' in self.cleaned_data.keys(): if self.cleaned_data['add_bank'] is True: bank = Bank(name=self.cleaned_data['new_bank']) project = super(ProjectForm, self).save() bank.save() project.bank.add(bank) property.project = project property.save() return project project = super(ProjectForm, self).save() property.project = project property.save() return project
def failed_banks_list(): """ This route is for a list of ALL banks. """ # The context for this pages is just "banks", a list of all banks. context = {"banks": Bank.select()} # Render the template to list.html and with the context from above. return render_template("list.html", **context)
def banks_ep(): sig = request.headers.get("X-Signature") content = request.json api_key = content["api_key"] nonce = content["nonce"] res, reason, api_key = check_auth(api_key, nonce, sig, request.data) if not res: return bad_request(reason) banks = Bank.from_user(db.session, api_key.user) banks = [bank.to_json() for bank in banks] return jsonify(banks)
class TestDindaBank(unittest.TestCase): def setUp(self): self.bank = Bank() def test_check_args(self): self.assertRaises(InvalidArgsException, checkArgs, ['python', 'file.csv', 'file2.csv', 'file3.csv']) self.assertRaises(InvalidArgsException, checkArgs, ['python', 'file.csv']) def test_load_non_existent_account_file(self): self.assertRaises(IOException, self.bank.loadAccountsFromCsv, 'non_existent_file.csv') def test_load_accounts_file_with_no_accounts(self): self.bank.loadAccountsFromCsv('test_resources/empty_accounts.csv') self.assertEquals(len(self.bank.accounts), 0) def test_load_accounts_from_valid_file(self): self.bank.loadAccountsFromCsv('test_resources/valid_accounts.csv') self.assertEquals(len(self.bank.accounts), 1) def test_load_invalid_accounts_file(self): self.assertRaises(InvalidFormatException, self.bank.loadAccountsFromCsv, 'test_resources/invalid_accounts_missing_value.csv') self.assertRaises(InvalidFormatException, self.bank.loadAccountsFromCsv, 'test_resources/invalid_accounts_missing_key.csv') def test_process_non_existent_transaction_file(self): self.assertRaises(IOException, self.bank.processTransactionsFromCsv, 'non_existent_file.csv') def test_process_and_match_account_with_transactions(self): self.test_load_accounts_from_valid_file() self.bank.processTransactionsFromCsv('test_resources/valid_transactions.csv') def test_process_transaction_file_with_no_transactions(self): self.bank.processTransactionsFromCsv('test_resources/empty_transactions.csv') def test_load_invalid_transaction_file(self): self.assertRaises(InvalidFormatException, self.bank.processTransactionsFromCsv, 'test_resources/invalid_transactions_missing_key.csv') def test_process_debit_transaction_with_fee(self): account = Account(1,0) account.processTransaction(-1) self.assertEquals(account.balance, -6) def test_process_debit_transaction(self): account = Account(1,101) account.processTransaction(-1) self.assertEquals(account.balance, 100) def test_process_credit_transaction(self): account = Account(1,0) account.processTransaction(1000) self.assertEquals(account.balance, 1000)
def add_banks(): name = request.args.get('name') bankHeadAddress = request.args.get('bankHeadAddress') bankUrl = request.args.get('bankUrl') bankSwiftCode = request.args.get('bankSwiftCode') try: bank = Bank(name=name, bankHeadAddress=bankHeadAddress, bankUrl=bankUrl, bankSwiftCode=bankSwiftCode) db.session.add(bank) db.session.commit() return "bank added. bank id={}".format(bank.id) except Exception as e: return (str(e))
def run(self, username, password, bank_name, token): try: bank_token = BankToken.get(token=token) except BankToken.DoesNotExist: raise Exception("token is not valid") if Bank.filter(bank_token=bank_token).exists(): raise Exception("token is consumed, use a new one!") try: manager = User.create_user(username, password) except IntegrityError as e: raise Exception("username is duplicate, please choose another") try: Bank.create(manager=manager, bank_name=bank_name, bank_token=bank_token) print("Welcome to virtual bank world ;)") except Exception as e: print(e) raise Exception('Some problem happened in creating bank')
def run(self): central_bank = self.get_central_bank() print("Total registered banks: %d" % Bank.select().count()) print() print("List of banks") index = 1 print('no\tname\tmanager\tbalance\tcustomer') columns_count = 5 print('-' * (8 * columns_count)) # TODO: filter by central bank for bank in Bank.select(): customers = Customer.filter(bank=bank) balance = bank.manager.wallet.get_balance() print('%d\t%s\t%s\t%.2f\t%d' % (index, bank.bank_name, bank.manager.username, balance, len(customers))) index += 1 print()
def run(self, username, password, bank_name): try: bank = Bank.get(bank_name=bank_name) except Bank.DoesNotExist: raise Exception("no bank exists with this name") try: user = User.create_user(username, password) except IntegrityError as e: raise Exception("username is duplicate, please choose another") try: Customer.create(user=user, bank=bank) print("Welcome to virtual bank world ;)") except Exception as e: print(e) raise Exception('Some problem happened in creating customer')
def transactions_fetcher(): truncate = lambda data, max: (data[:max - 3] + '...') if len( data) > max - 3 else data transactions_count = 0 transactions = json.loads(request.form['transactions']) for transaction in transactions: try: # Getting fields attributes = { 'user': g.user, 'bank': Bank.get(name=transaction.get('bank')), 'description': truncate(transaction.get('desc', ''), 256), 'amount': float(transaction.get('amount', '0').replace(',', '.') or 0), 'date': datetime.strptime(transaction.get('date'), '%d-%m-%Y') if transaction.get('date') else datetime.today() } # Fields validation if not attributes['description'] or not attributes['bank']: continue if attributes['date'] > datetime.today(): attributes['date'] = datetime.today() # Trying to find a category category = Categorizer.find_category(attributes['description']) # Creating transaction db_transaction = Transaction.get(**attributes) if db_transaction is None: db_transaction = add_to_db(Transaction(), **attributes) transactions_count += 1 # Finding or updating category if category is not None: db_transaction.category = category db_session.commit() except Exception as e: pass # Skip this transaction return HttpResponse('Transactions fetched.', {'count': transactions_count}, status=200)
def put_transactions(json_data, user): """Save a list of transactions into the database Args: json_data : str The json containing the bank and the transactions to add user : User The user to add to Returns: The number of transactions added """ bank = Bank.get(name=json_data.get('bank')) if bank is None: raise ValueError('Bank not supported.') added_transactions = 0 for t in json_data.get('transactions', []): transaction = set_attributes(Transaction(), user_id=user.user_id, bank_id=bank.bank_id) add_to_db(transaction, **t) added_transactions += 1 return added_transactions
def upload_transactions(): file = request.files.get('file') bank = Bank.get(bank_id=request.form.get('bank_id')) if bank is None: return HttpResponse("No bank was given.", status=400) # check if the post request has the file part if file is None or file.filename == '': return HttpResponse("No file was given.", status=400) if allowed_file(file.filename): filename = str(uuid.uuid4()) + os.path.splitext( secure_filename(file.filename))[1] relative_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) full_path = os.path.abspath(relative_path) # Saving file with unique name file.save(full_path) parsed = StatementParser(bank=bank).parse(full_path) if len(parsed['transactions']) > 0: added_transactions = put_transactions(parsed, g.user) transactions = Transaction.filter(user_id=g.user.user_id).order_by( Transaction.date.desc()).all() response = { "description": "Transactions uploaded.", "transactions": [t.as_dict() for t in transactions], "number": added_transactions } status = 200 else: response = "No transactions found." status = 204 os.remove(full_path) return HttpResponse(response, status=status) return HttpResponse("Error: Unauthorized file.", status=400)
def setUp(self): self.bank = Bank()
class Monopoly(object): ''' This is the game engine. :num_players: - number of players in game (see command-line interface.) :turns: - number of turns in game (see command-line interface.) :board: - by default, Board object using standard tiles. :cards: - by default, Cards object using standard game cards. ''' def __init__(self, num_players, board=Board(DEFAULT_TILES), cards=Cards()): self.num_players = num_players self.players = {} self.board = board self.bank = Bank(board, self.players) self.cards = cards self.turns = 0 def setup(self): ''' Factory method that sets up Player objects, and essential in-game elements e.g. the game logger. ''' print Style.BRIGHT + Fore.WHITE + "\nWelcome to command-line Monopoly! Let's set your game up.\n" # creates all players for player in range(1, self.num_players + 1): name = raw_input("What's your name player? > ") self.players[name] = Player(name, self.board, self.cards) # includes name of other players, for future interaction purposes for player in self.players.values(): player.others = [other for other in self.players.values() if other != player] print "Player %s has been added to game." % (player.name) self.cards.shuffle_cards() # set up interactor Interactor.players = self.players Interactor.board = self.board Interactor.bank = self.bank Interactor.cards = self.cards Interactor.db = DbInterface() print 'Interactor Initialized!' # set up game logger GameLogger.players = self.players GameLogger.player_logs = {p: [] for p in self.players} print 'Game logger initialized!' return "Setup complete" def turn(self): ''' Advances game state - orchestrates a turn for each player using the Player.roll_dice() method.''' for player in self.players.values(): print "\n%s, it's your turn now!" % player.name player.inspect_self() current_location = player.roll_dice(self.board, self.bank) if current_location is not None: player.interact(current_location, self.board, self.bank) if player.money < 0: pass # bankrupcty protocol player.check_monopoly() self.bank.update_all_rents(self.players) GameLogger.push_public_logs() msg = "\n -- End of Turn %s. \n" % self.turns GameLogger.add_log(msg=msg) self.turns += 1 return def play(self, turns, mode): ''' Runs the game, following setup, for a duration specified by the command-line argument, 't' (50 by default).''' for _ in range(turns): self.turn() self.summary() self.select_winner(mode) return def select_winner(self, mode='default'): ''' After the game ends, process who the game winners are based on requirements set by game mode. ''' if mode == 'default': for player in self.players.values(): if player._inplay is True: print "%s is the winner!" % player.name elif mode == 'worth': winner_worth = 0 winner_name = None for player in self.players.values(): if player.net_worth()[0] > winner_worth: winner_worth = player.net_worth()[0] winner_name = player.name print Fore.GREEN + Style.BRIGHT + "%s is the winner!" % winner_name def summary(self): ''' Summary stats displayed following the game. ''' print "_"*40 print ' '*5, 'G A M E S U M M A R Y', ' '*5 print '%s turns have elapsed in this game.\n' % self.turns for player in self.players.values(): print "Player: %s" % player.name print "Total Net Worth: $%s" % player.net_worth()[0] print "Money: $%s" % player.money print "%% Net Worth in Cash: %s" % player.net_worth()[1] print "%% Net Worth in Assets: %s" % player.net_worth()[2] print "Emergency Liquidity: $%s" % (player.net_worth()[0] * player.net_worth()[2]) property_display = [p.name for p in player.properties.values()] print "Properties: %s" % property_display print "Monopolies: %s\n\n" % player.check_monopoly()
objects as sumed by you and the functions defined. """ """ Bank facilities assumed 1. Create Bank Account 2. Deposit Money 3. Withdraw Money 4. Update Details 5. Check Account Balance 6. View Transaction History """ from models import User, Bank import helpers bank = Bank() print( "Hey, Welcome to the bank!", "Please fill some details to create your bank account: ", sep="\n", ) input_data = helpers.create_bank_account() print("*" * 30, "Succesfully created account :)", sep="\n") # Create new user instance using data received from input_data user = User( input_data.get("name"), input_data.get("mobile"), input_data.get("pin"),
user_Input_skill = input('What is their skill level? ') user_Input_Cut = input('What is their take on this score ') new_Hacker = Hacker(user_Input_Name, int(user_Input_skill), int(user_Input_Cut)) rolodex.append(new_Hacker) break else: print( f'{user_Input_Specialty} is not a speciality. Please enter a valid speciality.' ) # create bank cash = random.randint(50000, 1000000) alarm_Score = random.randint(0, 100) vault_Score = random.randint(0, 100) sec_Score = random.randint(0, 100) national_Bank = Bank(cash, alarm_Score, vault_Score, sec_Score) # create dictionary for report bank_scores = { "alarm": alarm_Score, "vault": vault_Score, "security": sec_Score } most_Secure = max(bank_scores.items(), key=operator.itemgetter(1))[0] least_Secure = min(bank_scores.items(), key=operator.itemgetter(1))[0] print('-------RECON REPORT-------') print( f'The most secure part of the job is the {most_Secure}. Least Secure is {least_Secure}.' ) print('--------------------------') # choose crew
def insertInitialAmount(request): print 'bank.insert' if request.method == 'POST': b = Bank(initialAmount=request.POST["initialAmount"]) b.save() return HttpResponseRedirect('/')
import sys from models import Bank from models import InvalidArgsException def checkArgs(args): if len(args) != 3: raise InvalidArgsException if __name__ == '__main__': print('- Welcome do Dinda Bank') checkArgs(sys.argv) dinda = Bank() dinda.loadAccountsFromCsv(sys.argv[1]) dinda.processTransactionsFromCsv(sys.argv[2]) print dinda
def init_data(db): print('Generating data ...') from models import Bank, Customer, Account, Saveacc, Checkacc, Cusforacc, Loan, Cusforloan, Department, Employee db.session.query(Cusforloan).delete() db.session.query(Cusforacc).delete() db.session.query(Saveacc).delete() db.session.query(Checkacc).delete() db.session.query(Loan).delete() db.session.query(Customer).delete() db.session.query(Account).delete() db.session.query(Employee).delete() db.session.query(Department).delete() db.session.query(Bank).delete() bank_data = fake_bank() for bank in bank_data: if not Bank.query.filter_by(bankname=bank['bankname']).first(): new_bank = Bank(**bank) db.session.add(new_bank) db.session.commit() department_data = fake_department() for department in department_data: if not Department.query.filter_by( departID=department['departID']).first(): new_depart = Department(**department) db.session.add(new_depart) db.session.commit() emp_data = fake_emp(department_data) for emp in emp_data: if not Employee.query.filter_by(empID=emp['empID']).first(): new_emp = Employee(**emp) db.session.add(new_emp) db.session.commit() cus_data = fake_cus(bank_data, emp_data) for cus in cus_data: if not Customer.query.filter_by(cusID=cus['cusID']).first(): new_cus = Customer(**cus) db.session.add(new_cus) db.session.commit() acc_data, cusforacc_data, saveacc_data, checkacc_data = fake_acc( bank_data, cus_data) for acc in acc_data: if not Account.query.filter_by(accountID=acc['accountID']).first(): new_acc = Account(**acc) db.session.add(new_acc) for cusforacc in cusforacc_data: if not Cusforacc.query.filter_by(accountID=cusforacc['accountID'], cusID=cusforacc['cusID']).first(): new_cusforacc = Cusforacc(**cusforacc) db.session.add(new_cusforacc) for saveacc in saveacc_data: if not Saveacc.query.filter_by(accountID=saveacc['accountID']).first(): new_saveacc = Saveacc(**saveacc) db.session.add(new_saveacc) for checkacc in checkacc_data: if not Checkacc.query.filter_by( accountID=checkacc['accountID']).first(): new_checkacc = Checkacc(**checkacc) db.session.add(new_checkacc) db.session.commit() loan_data, cusforloan_data = fake_loan(bank_data, cus_data) for loan in loan_data: if not Loan.query.filter_by(loanID=loan['loanID']).first(): new_loan = Loan(**loan) db.session.add(new_loan) for cusforloan in cusforloan_data: if not Cusforloan.query.filter_by(loanID=cusforloan['loanID'], cusID=cusforloan['cusID']).first(): new_cusforloan = Cusforloan(**cusforloan) db.session.add(new_cusforloan) db.session.commit() print('Generation finished !')