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

后端 未结 6 1643
难免孤独
难免孤独 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 03:08

    >>> from werkzeug.datastructures import ImmutableMultiDict
    >>> so = ImmutableMultiDict([('default', u''), ('required', u'on'), ('name', u'short_text'), ('name', u'another'), ('submit', u'Submit')])
    
    # Most earlier answers have comments suggesting so.to_dict()
    # It doesn't work, duplicates are lost like in a normal dict
    >>> so.to_dict()
    {'default': '', 'required': 'on', 'name': 'short_text', 'submit': 'Submit'}
    
    # The response by Vb407 is better but litters lists everywhere
    >>> dso = dict(so)
    {'default': [''], 'required': ['on'], 'name': ['short_text', 'another'], 'submit': ['Submit']}
    
    # We can achieve the requested state by cleaning this up
    >>> { k: dso[k][0] if len(dso[k]) <= 1 else dso[k] for k in dso }
    {'default': '', 'required': 'on', 'name': ['short_text', 'another'], 'submit': 'Submit'}
    

提交回复
热议问题