Falcon: No data in request.stream.read()

Created on 4 Mar 2019  路  3Comments  路  Source: falconry/falcon

Hi,

I'm not sure if I'm doing something wrong or if it's a bug. My issue is that I POST send data to my resource, but the body is always empty


class View(object):
    def on_post(self, req, resp):
        # If Content-Length happens to be 0, or the header is
        # missing altogether, this will not block.
        data = req.stream.read(req.content_length or 0)

        logger.debug('content length: %s', req.content_length)
        logger.debug('Received body: %s', data)

        # do something 
        return {'status': 'ok'}

I tested the view with curl

curl -i -XPOST \
    -H "Accept:application/json" \
    -H "Content-Type:application/json" \
    http://localhost:8000/jobs/fetch-competitions?async=1 \
    -d '{"competitionId": 2, "seasonId": 1}' 

I also tried --data-raw option and it's not working. In both case I'm getting the following logs

2019-03-04 03:37:48,760 - jobs - DEBUG - content length: 35
2019-03-04 03:37:48,761 - jobs - DEBUG - Received body: b''
2019-03-04 03:37:48,762 - gunicorn.error - ERROR - Error handling request /jobs/fetch-competitions?async=1
needs-information question

All 3 comments

Hi @benzid-wael !
Unfortunately (or fortunately... :slightly_smiling_face: ) I cannot really reproduce your issue, be it a bug or anything else.

I have slightly modified your example, but that was mostly filling in the missing parts, as well as replacing your stream handling with resp.bounded_stream which does what you want out of the box (but your code does the job too, so no issue there):

import logging

import falcon

logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.DEBUG)
logger = logging.getLogger('api.demo')


class View(object):

    def on_post(self, req, resp):
        data = req.bounded_stream.read()

        logger.debug('content length: %s', req.content_length)
        logger.debug('Received body: %s', data)

        # do something

        resp.media = {'status': 'ok'}


api = falcon.API()
api.add_route('/jobs/fetch-competitions', View())

Issuing your curl request yields the following log output:

2019-03-04 19:00:42,541 - api.demo - DEBUG - content length: 35
2019-03-04 19:00:42,541 - api.demo - DEBUG - Received body: b'{"competitionId": 2, "seasonId": 1}'

I have used Python 3.7.2 and

falcon==2.0.0a1
gunicorn==19.9.0
pkg-resources==0.0.0

However, I have quickly tested even the current stable Falcon 1.4.1 and Python 2.7, seems to work fine too.

Which versions are you using? Are you using any special components/middleware?

Kindly,
Vytas

Hi again @benzid-wael !
Have you had a chance to review my suggestions?

We are closing this issue hoping that you have already resolved the problem, but not hesitate to reopen if this is not the case!

Was this page helpful?
0 / 5 - 0 ratings