Exception in making a REST call
<p>I am currently working on a REST call using Flask Framework. and I have run into some errors along the way, which I am unable to figure out as to why they occur (still trying though). The error is as shown below:</p>

<pre><code>[2016-09-20 18:53:26,486] ERROR in app: Exception on /Recommend [GET]
Traceback (most recent call last):
  File "/anaconda/lib/python2.7/site-packages/flask/app.py", line 1988, in wsgi_app
    response = self.full_dispatch_request()
  File "/anaconda/lib/python2.7/site-packages/flask/app.py", line 1641, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/anaconda/lib/python2.7/site-packages/flask_cors/extension.py", line 161, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
  File "/anaconda/lib/python2.7/site-packages/flask_api/app.py", line 97, in handle_user_exception
    for typecheck, handler in chain(blueprint_handlers.items(), app_handlers.items()):
AttributeError: 'tuple' object has no attribute 'items'
127.0.0.1 - - [20/Sep/2016 18:53:26] "GET /Recommend HTTP/1.1" 500 -
</code></pre>

<p>here is the code that I have built:</p>

<pre><code>from flask import request, jsonify
from flask_api import FlaskAPI
from flask_cors import CORS

from sets import Set
from collections import defaultdict
import itertools
import copy

app = FlaskAPI(__name__)
CORS(app)

content = None

class Apriori:    
    def __init__(self):
        self.no_of_transactions = None
        self.min_support = 0.5
        self.min_confidence = 0.75
        self.transactions = {}
        self.set_of_items = set()
        self.frequencies = {}
        self.frequent_itemsets_of_order_n = {}
        self.association_rules = {}

    def createPowerSet(self,s):
        powerset = set()
        for i in xrange(2**len(s)):
            subset = tuple([x for j,x in enumerate(s) if (i &gt;&gt; j) &amp; 1])
            if len(subset) == 0:
                pass
            elif len(subset) == 1:
                powerset.add(subset[0])
            else:
                powerset.add(subset)
        return powerset

    def createFrequentItemSets(self,set_of_items,len):
        frequent_itemsets = set(itertools.combinations(set_of_items, len))
        for i in list(frequent_itemsets):
            tempset = set(i)
            self.frequencies[i] = 0
            for k, v in self.transactions.iteritems():
                if tempset.issubset(set(v)):
                    self.frequencies[i] += 1
            if float(self.frequencies[i])/self.no_of_transactions &lt; self.min_support:
                frequent_itemsets.discard(i)
        return frequent_itemsets

    def mineAssociationRules(self,frequent_itemset):
        s = set(frequent_itemset)
        subs = list(self.createPowerSet(s))
        for each in subs:
            if sorted(tuple(set(each))) == sorted(tuple(s)):
                continue            
            if len(set(each))==1:
                antecedent = list(set(each))[0]
            elif len(set(each))&gt;1:
                antecedent = tuple(set(each))

            if len(s.difference(set(each)))==1:
                consequent = list(s.difference(set(each)))[0]
            elif len(s.difference(set(each)))&gt;1:
                consequent = tuple(s.difference(set(each)))               
            AuC = tuple(s)        
            if float(self.frequencies[AuC])/self.frequencies[antecedent] &gt;= self.min_confidence:
                if antecedent in self.association_rules:
                    pass
                else:
                    if type(antecedent) is tuple:
                        antecedent = (",").join(antecedent)
                    if type(consequent) is tuple:
                        consequent = (",").join(consequent)
                    self.association_rules[antecedent] = consequent

    def implement(self,transactions):
        #for i in range(0,self.no_of_transactions):
        for i in range(0,len(transactions)):
            self.transactions["T"+str(i)] = defaultdict(list)
            self.transactions["T"+str(i)] = transactions[i].split(',')
            self.set_of_items = self.set_of_items.union(Set(self.transactions["T"+str(i)]))         
        for i in list(self.set_of_items):
            self.frequencies[i] = 0
            for k, v in self.transactions.iteritems(): 
                if i in v:
                    self.frequencies[i] = self.frequencies[i] + 1
            if float(self.frequencies[i])/self.no_of_transactions &lt; self.min_support:
                self.set_of_items.discard(i)                
        self.frequent_itemsets_of_order_n[1] = self.set_of_items
        l = 1        
        reps = copy.deepcopy(self.set_of_items)
        while True:
            l += 1
            result = self.createFrequentItemSets(self.set_of_items, l)
            if len(result) == 0:
                break
            self.frequent_itemsets_of_order_n[l] = result
            reps = copy.deepcopy(self.frequent_itemsets_of_order_n[l])        
        l = l-1         
        while l&gt;2:
            for each in self.frequent_itemsets_of_order_n[l]:
                self.mineAssociationRules(each)
            l = l-1

@app.route('/Recommend')
def FindAssociations():
    transactions = ["A,C,D,F,G","A,B,C,D,F","C,D,E","A,D,F","A,C,D,E,F","B,C,D,E,F,G"]
    apr = Apriori()
    apr.implement(transactions)
    return jsonify(rules=apr.association_rules)

if __name__ == "__main__":
    app.run(port=5000)
</code></pre>

<p>I did run some sample code found on the web, and built the above script based on those scripts. They worked out well. The class I built was based on another python program that I had built earlier which worked well. Should I have imported the class from another script instead of building it here?</p>

<p>There are a number of errors in your <code>Apriori</code> which need to fixed. There are a few attempts to divide by <code>self.no_of_transactions</code> (e.g. line 87) which is initialised to <code>None</code> and never changed. Dividing by <code>None</code> raises an exception:</p>

<pre><code>&gt;&gt;&gt; 1/None
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
TypeError: unsupported operand type(s) for /: 'int' and 'NoneType'
</code></pre>

<p>This exception is then handled in Flask-API's <code>handle_user_exception()</code> method, which also appears to have a bug as shown in the exception it raises.</p>

<p>The way to fix it is to correct your code so that it does not divide by <code>None</code>.</p>

python flask