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


Question

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 often enough to have a ready-made solution.

So what Flask give me is something like:

ImmutableMultiDict([('default', u''), ('required': u'on'), ('name', u'short_text'), ('name', u'another'), ('submit', u'Submit')])

And what I am looking to get is something close to this:

{
  'default': '',
  'name': ['short_text', 'another'],
  'required': true
}
1
34
8/21/2015 6:00:04 AM

Accepted Answer

>>> from werkzeug.datastructures import ImmutableMultiDict
>>> imd = ImmutableMultiDict([('default', u''), ('required', u'on'), ('name', u'short_text'), ('name', u'another'), ('submit', u'Submit')])
>>> imd.to_dict(flat=False)
>>> {'default': [''], 
'name': ['short_text', 'another'],
'required': ['on'],
'submit': ['Submit']}

.to_dict(flat=False) is the thing to keep in mind. See the relevant documentation

44
2/15/2018 4:56:43 PM

The Flask ImmutableMultiDict data structure has a built in to_dict method.

This knowledge in addition to the Flask request object form property being an ImmutableMultiDict allows for simple handling of a form POST request to MongoDB.

See below for a naive example:

from flask import request

@app.route('/api/v1/account', methods=['POST'])
def create_account():
    """Create user account"""
    account_dict = request.form.to_dict()

    db.account.insert_one(account_dict)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon