How to make Flask request.form return ordered dict data?

589 Views Asked by At

I currently have a form on my flask web app that has +- 100 inputs. To request every value in 1 line I use: f = request.form. If I print it on my local version, I'll end up with a complete list of all my values in complete order:

ImmutableMultiDict([('intro1', 'hello'), ('intro2', 'eargr'), ('intro3', 'rferferaf'), ('intro4', 'eragaerg'), ('intro5', 'aergferaf'), ('intro6', 'aerfa'), ('intro7', 'faf'),`('intro8', 'fazfa'), ('intro9', 'f'), ('intro10', 'f'), ('intro11', 'f'), ('intro12', 'ezfzef'),` ('intro13', 'f'), ('liab1', ''), ('liab2', 'hello'), 
    ('liab3', ''), ('liab4', 'nvion'),....

If I print it on my live version, it will return it in a complete random order:

ImmutableMultiDict([('liab43', 'hello'), ('pl33', ''), ('inv3', ''), ('fin5', ''), ('inv10', ''), `('pl44', ''), ('liab46', ''), ('liab17', ''), ('liab49', ''), ('intro10', 'ovov o'), ('fin9', ''), ('pl30', ''), ('pl15', ''), ('liab10', ''), ('pl34', 'hello'), ('pl24', ''), ('intro13', 'nvion'), ('liab31', ''), ('pl39', ''), ('intro3', 'zenfoczoi'), ('liab1', ''), ('inv15', ''), ('pl16', ''), ('liab50', ''), ('intro1', 'hello'), ('intro8', 'connfvo'), ('pl38', ''), ('fin4', ''), ('pl49', ''), ('pl21', ''), ('fin6', ''), ('intro2', 'hefhuze'), ('liab22', ''), ('pl61', ''), ('pl18', ''), ('fin10', ''), ('liab53', ''), ('liab30', ''),`

How can I fix this? Because both version are completely the same, no difference. Local version is on Windows and live version on a Debian VPS using nginx & gunicorn.

1

There are 1 best solutions below

1
Grey Li On BEST ANSWER

By default, when you call request.form, Flask return a ImmutableMultiDict (immutable dict), but you can also let it return ImmutableOrderedMultiDict (ordered immutable dict) if you want the data in order. Just do this:

from flask import Flask, Request
from werkzeug.datastructures import ImmutableOrderedMultiDict

class MyRequest(Request):
    """Request subclass to override request parameter storage"""
    parameter_storage_class = ImmutableOrderedMultiDict

class MyFlask(Flask):
    """Flask subclass using the custom request class"""
    request_class = MyRequest

app = MyFlask(__name__)