【问题标题】:filter by mutiple arguement coma value flask sqlalchemy postgresql按多个参数逗号值过滤烧瓶sqlalchemy postgresql
【发布时间】:2022-01-14 23:30:37
【问题描述】:

我收到一个类似这样的获取请求:

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

我想要的只是通过数据库中的逗号值过滤。像这样的东西:

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()

这是表格的样子:

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

我只想要 get 参数中提到的 a、b、c 值如何在参数烧瓶中按这些 coma 值过滤?

【问题讨论】:

    标签: python flask sqlalchemy


    【解决方案1】:

    你应该将参数传递给text方法:

    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()
    

    这个话题可能会有所帮助:SQLAlchemy IN clause

    【讨论】:

      【解决方案2】:

      我建议你这样做:

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

      这种方法应该更安全。

      【讨论】:

      • 我不建议让公共 API 依赖于参数集。如果有'd'参数怎么办?你必须改变你的端点......而且你不向后兼容
      • 如果他不能很好地清理他的参数,他将面临比兼容性问题更多的麻烦。
      • 但是他可以清理查询字符串中的参数
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-29
      • 1970-01-01
      • 2021-11-22
      • 2016-01-15
      • 2021-05-20
      • 1970-01-01
      相关资源
      最近更新 更多