Falcon: JSON load can't read req.stream on POST request

Created on 26 Apr 2017  路  3Comments  路  Source: falconry/falcon

As the title says, after my POST request, json.load seems that he can't read the req.stream. Here's my unworking code :

class Register(object):
    def on_post(self, req: falcon.Request, resp: falcon.Response):
        data = json.load(req.stream)

And here's what uWSGI returns me when I do my POST request :

Traceback (most recent call last):
  File "/home/bachrc/dev/serveur-rest-dg2r/env/lib/python3.5/site-packages/falcon/api.py", line 209, in __call__
    responder(req, resp, **params)
  File "./controllers/shop/register.py", line 16, in on_post
    data = json.load(req.stream)
  File "/usr/lib/python3.5/json/__init__.py", line 268, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "/usr/lib/python3.5/json/__init__.py", line 312, in loads
    s.__class__.__name__))
TypeError: the JSON object must be str, not 'bytes'

I'm using the Chromium extension Postman to do my POST requests.

I actually tried a lot of things, and with this bribe of code, I can read the answer :

class Register(object):

    def on_post(self, req: falcon.Request, resp: falcon.Response):
        data = json.loads(str(req.stream.read().decode("utf-8")))

I'm not convinced of the efficiency, or the performance of this solution tho'. It's more a trick than an actual solution. And the documentation says json.load(req.stream) is safe, but is obviously not.

Most helpful comment

Okay. So it seems that to use your example, you should be in Python 3.6, and I was in 3.5 . Lost 3 hours for this. https://docs.python.org/3/library/json.html#json.load

All 3 comments

Okay. So it seems that to use your example, you should be in Python 3.6, and I was in 3.5 . Lost 3 hours for this. https://docs.python.org/3/library/json.html#json.load

I just did the same thing. That was painful.

Can't you use req.media ?

Was this page helpful?
0 / 5 - 0 ratings