1

Usually request.json is used to access json objects send to a flask view. I would like to assign something to request.json

from flask import request
print("request.json = ", request.json)
print("request.form['json'] = ", request.form['json'])
request.json = jsonify(request.form['json'])

leads to

request.json =  None
request.form['json'] =  {
    "test": "test"
}
Traceback (most recent call last):
 ...
  File "/ajax_handlers.py", line 952, in X
    request.json = jsonify(request.form['json'])
  File "/opt/anaconda3/lib/python3.7/site-packages/werkzeug/local.py", line 365, in <lambda>
    __setattr__ = lambda x, n, v: setattr(x._get_current_object(), n, v)
AttributeError: can't set attribute

Any idea how I can assign a json object to request.json?

4
  • Why do you want to change the request? Commented Jun 14, 2020 at 12:09
  • just to make sure the request object always has the content expected in the code later on... this would be the easiest change of the existing code Commented Jun 14, 2020 at 12:10
  • This issue happens because you can't set request.json. So, instead use x = jsonify(request.form['json']) and x will be the response Commented Jun 14, 2020 at 12:40
  • but x will not have the same properties... for example x.get('') will not work... Commented Jun 14, 2020 at 12:45

1 Answer 1

1

Presumably for safety, you cannot replace the values on a request object; they come in from the client, and they remain as-is. When you think about it, that's good practice; if various pieces of code try to modify your request object's data in various ways, it would lead to inconsistent and hard-to-test code.

As an alternative, you can assign meaningful attributes that aren't part of the default request object. For example, perhaps you're trying to remember, for elsewhere in your stack, who the user is authenticated as:

# Don't do this!
flask.request.json['authenticated_user'] = authenticated_user

That's messing with the original request data; don't do that. It'll make debugging (not to mention security) a nightmare. A better alternative:

# Do this instead
flask.request.authenticated_user = authenticated_user

You can add to the existing request with new attributes, but you can't go replacing existing properties on the request. Nor should you try!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.