Search code examples
web2py

Web2Py Error - TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'


I am getting an error when I try to run the code for Web2Py.

Basically we have to write a function that would query the database and show the flights available.

The function is defined as below:

def searchFlights():
    return dict()

def show():
    receivedFlights = request.vars.originCity+','+request.vars.destCity+','+request.vars.type+','+request.vars.deptDate+','+request.vars.arrivalDate+','+request.vars.vlassType+','+request.vars.noOfAdults+','+request.vars.noOfChildren+','+request.vars.noOfInfants
    return dict(txt1=recievedflights, flights=db().select(db.Flight.request.originCity+','+request.vars.destCity+','+request.vars.type+','+request.vars.deptDate+','+request.vars.arrivalDate+','+request.vars.classType+','+request.vars.noOfAdults+','+request.vars.noOfChildren+','+request.vars.noOfInfants)) 

The error we are getting right now is:

  File "K:/wdd-softw/web2py/applications/Assignment/controllers/default.py", line 106, in show
    receivedFlights = request.vars.originCity+','+request.vars.destCity+','+request.vars.type+','+request.vars.deptDate+','+request.vars.arrivalDate+','+request.vars.vlassType+','+request.vars.noOfAdults+','+request.vars.noOfChildren+','+request.vars.noOfInfants
  TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

Solution

  • The first problem is that when the page with the form first loads, nothing has been submitted, so request.vars is empty and therefore each request.vars.some_var returns None. Instead, you could do something like this:

    receivedFlights = ', '.join(request.vars.values()) if request.vars else 'Empty'
    

    You'll have the same problem with your database select -- you should only run the query when request.vars exists. Furthermore, your query is incorrect -- you cannot simply concatenate all the values into a single string and put that in the select(). I suggest you read the chapter on the DAL for proper query syntax. It should look more like:

    db((db.Flight.originCity == request.vars.originCity) &
       (db.Flight.destCity == request.vars.destCity) &
       ...).select()
    

    Finally, you can simplify the query construction, as suggested here:

    query = reduce(lambda a, b: (a & b),
        (db.mytable[v] == request.vars[v] for v in request.vars if v != None))