0

I am receiving a get request something like this:

http://127.0.0.1:5000/stockList?name=a,b,c,

All i want is filter by those coma value from database.Something like this:

name = request.args.get('name', None)
connection = db.engine.connect(close_with_result=True)

sql = text("""select * from stockstatus where name='a' or name='b' or name='c'""")
connection.execute(sql)
connection.close()

This is how table looks like:

--  id |  name  |
-- ----+---------
--  1  | a       | 
--  2  | b       |
--  3  | c      | 
--  4  | d      | 
--  5  | e      | 

I only want a,b,c value mentioned in the get argument How can i filter by those coma value in arguement flask?

davidism
  • 121,510
  • 29
  • 395
  • 339
jack
  • 351
  • 5
  • 23

2 Answers2

0

You should pass parameters to text method:

name = request.args.get('name')
if name:
   names = name.split(',')
else:
   names = []
connection = db.engine.connect(close_with_result=True)

sql = text("""select * from stockstatus where name IN :names""", names=tuple(names))
connection.execute(sql)
connection.close()

This topic can be helpful: SQLAlchemy IN clause

jorzel
  • 1,216
  • 1
  • 8
  • 12
0

I would suggest you to do something like this:

@app.route('/stockList/<a>/<b>/<c>')
def stockList(a=None, b=None, c=None):

This method should be safer.

TwoZed3
  • 64
  • 3
  • I would not recommend making public API dependendent on set of parameters. What if there would be 'd' param? You have to change your endpoint...and you are not backward compatible – jorzel Dec 10 '21 at 10:49
  • If he doesn't sanitize his parameter well he'll be in more trouble than compatibility issues. – TwoZed3 Dec 10 '21 at 16:25
  • But he can sanitize param from querystring – jorzel Dec 10 '21 at 16:51