Reputation: 459
NOTE: This is not a duplicate of How to set attributes on a request in Flask
Case: Knowing full well what you are about to do isn't the proper way, but it's 29th of Dec and the people who can make the real fixes, won't be available for a week yet. After a recent change, a page (or is it more than one?) no longer POSTs JSON, but the FORM. You might be able to fix this for a week by converting the request.form
into JSON and slapping it into request.json
- if it would just allow you to do that.
What I tried was:
if not request.json and request.form:
setattr(request, "json", json.dumps(request.form))
I get the complaint:
...
File "/usr/lib/python3/dist-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "./routes.py", line 134, in api_file_id
setattr(request, "json", json.dumps(request.form))
File "/usr/lib/python3/dist-packages/werkzeug/local.py", line 364, in <lambda>
__setattr__ = lambda x, n, v: setattr(x._get_current_object(), n, v)
AttributeError: can't set attribute
Being able to do this would make this bubblegum-fix small and easy to locate (in a route function). Alternatives get messy...
I lack the necessary knowledge to understand why am I getting this error, nor does it give me much to work with - why can't the attribute be set.
Am I doing something wrong or is this supposed to be impossible for some reason?
Upvotes: 0
Views: 1056
Reputation: 2050
The underlying BaseRequest
object is immutable, so you can't modify request
. You may need to create a new variable to hold the json, which will mean you will need to update other code to reference your new variable, instead of request.json
, e.g:
if not request.json and request.form:
myjson = json.dumps(request.form)
Upvotes: 1