Home > Software design >  filter by mutiple arguement coma value flask sqlalchemy postgresql
filter by mutiple arguement coma value flask sqlalchemy postgresql

Time:12-10

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?

CodePudding user response:

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

CodePudding user response:

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.

  • Related