In Flask convert form POST object into a representation suitable for mongodb

后端 未结 6 1623
难免孤独
难免孤独 2020-12-03 02:09

I am using Flask and MongoDB. I am trying to convert the content of request.form into something suitable for saving via PyMongo. It seems like something that should come up

6条回答
  •  一向
    一向 (楼主)
    2020-12-03 02:51

    You can use werkzeug's getlist to write code like this

    data = dict((key, request.form.getlist(key)) for key in request.form.keys())
    

    Now each key of data would be a list which would contain 1 more element. To get results exactly in your format do this

    data = dict((key, request.form.getlist(key) if len(request.form.getlist(key)) > 1 else request.form.getlist(key)[0]) for key in request.form.keys())
    

    Now this is inefficient because for each key there are 3 calls to request.form.getlist(key). You can write a loop and get around it.

提交回复
热议问题