edit: think solved it, added answer.
i writing rest api using python, falcon web framework , pydal dal mysql.
i want filter(where statement) using fields in query string of request.
for example receive the following request:
http://127.0.0.1:5000/users?firstname=firstn&id=1
and want pydal query generate following sql:
select * users firstname = 'firstn' , id = '1'
i not find can because pydal receive like:
self.db((self.db.users.id == 1) & (self.db.users.firstname == 'firstn')).select()
but can't specify fields because don't know field going filter on, thats why wrote this:
def on_get(self, req, resp): if req.query_string not '': input = req.query_string sql = 'select * users ' sql += ' , '.join(['{col} = \'{value}\''.format(col=item.split('=')[0], value=item.split('=')[1]) item in input.split('&')]) resp.body = json.dumps(self.db.executesql(sql, as_dict=true)) else: resp.body = json.dumps(self.db(self.db.users).select().as_dict())
but think is awful , should better why.
i created function receives table object , query string , does:
def generate_filter(table, query_string): statement = true field in query_string.split('&'): field = field.split('=') statement &= getattr(table, field[0]) == field[1] return statement
than execute:
self.db(generate_filter(self.db.users, req.query_string)).select().as_dict()
Comments
Post a Comment