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

后端 未结 6 1641
难免孤独
难免孤独 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:00

    Comparison of dict() and .to_dict() method before and after python version 3.6.

    from werkzeug.datastructures import ImmutableMultiDict
    imd = ImmutableMultiDict([('default', u''), ('required', u'on'), ('name', u'short_text'), ('name', u'another'), ('submit', u'Submit')])
    

    Till python3.5

    dict(imd)
    #output: {'default': [''], 'required': ['on'], 'name': ['short_text', 'another'], 'submit': ['Submit']}
    
    imd.to_dict(flat=false)
    #output: {'default': [''], 'required': ['on'], 'name': ['short_text', 'another'], 'submit': ['Submit']}
    
    imd.to_dict(flat=True) # or imd.to_dict() 
    #output: {'default': '', 'required': 'on', 'name': 'short_text', 'submit': 'Submit'}
    

    Thus,

    dict(imd) == imd.to_dict(flat=False)
    #output: True
    

    From python3.6 onwards

    dict(imd)
    #output: {'default': '', 'required': 'on', 'name': 'short_text', 'submit': 'Submit'}
    
    imd.to_dict(flat=false)
    #output: {'default': [''], 'required': ['on'], 'name': ['short_text', 'another'], 'submit': ['Submit']}
    
    imd.to_dict(flat=True) # or imd.to_dict() 
    #output: {'default': '', 'required': 'on', 'name': 'short_text', 'submit': 'Submit'}
    

    Thus,

    dict(imd) == imd.to_dict(flat=False)
    #output: False
    

    Using .to_dict() with flat=True/False is a safer option.

提交回复
热议问题