databaseweb.py

bad use of variables in db.query


I'm trying to develop a blog using webpy.

def getThread(self,num):
        myvar = dict(numero=num)
        print myvar
        que = self.datab.select('contenidos',vars=myvar,what='contentTitle,content,update',where="category LIKE %%s%" %numero)
      
        return que

I've used some of the tips you answer in this web but I only get a

<type 'exceptions.NameError'> at / global name 'numero' is not defined

Python C:\xampp\htdocs\webpy\functions.py in getThread, line 42 Web GET http://:8080/ ...

I'm trying to make a selection of some categorized posts. There is a table with category name and id. There is a column in the content table which takes a string which will be formatted '1,2,3,5'.

Then the way I think I can select the correct entries with the LIKE statement and some %something% magic. But I have this problem.

I call the code from the .py file which builds the web, the import statement works properly getThread is defined inside this class:

class categoria(object):
    def __init__(self,datab,nombre):
        
        self.nombre = nombre
        self.datab = datab
        self.n = str(self.getCat()) #making the integer to be a string 
        self.thread = self.getThread(self.n)
        return self.thread
    
    def getCat(self):
        '''
        returns the id of the categorie (integer)
        '''
        return self.datab.select('categorias',what='catId', where='catName = %r' %(self.nombre), limit=1)

Solution

  • Please check the correct syntax for db.select (http://webpy.org/cookbook/select), you should not format query with "%" because it makes code vulnerable to sql injections. Instead, put vars in dict and refer to them with $ in your query.

    myvars = dict(category=1)
    db.select('contenidos', what='contentTitle,content,`update`', where="category LIKE '%'+$category+'%'", vars=myvars)
    

    Will produce this query:

    SELECT contentTitle,content,`update` FROM contenidos WHERE category LIKE '%'+1+'%'
    

    Note that I backquoted update because it is reserved word in SQL.