How to Mutate Flask's requests.args - ImmutableMultiDict

Viewed 12

I have a query parameter that is used in most of my APIs.

In the @app.beforerequest decorator, I would like to pop this query parameter from request.args, do something with it, and then prevent this query parameter from being accessible in the route function.

@app.before_request
def before_request():
    foo = request.args.pop('foo')

@app.get('/')
def home():
    # foo parameter is no longer accessible in the route function
    assert 'foo' not in request.args

Given that request.args is an ImmutableMultiDict, pop of course does not work.

Neither is it OK to set request.args for example: request.args = {k: v for k, v in request.args if k != 'foo'}.

One option is to set the parameter_storage_class to MultiDict:

class MyRequest(Request):
    parameter_storage_class = MultiDict

app = Flask(__name__)
app.request_class = MyRequest

However, I am not clear what are the consequences of using MultiDict instead of ImmutableMultiDict. The docs present the following note without elaborating on the reason why:

It possible to use mutable structures, but this is not recommended.

0 Answers
Related