Acorn
Acorn

Reputation: 50497

Accessing raw request string from Flask app

Is it possible to access the raw, unparsed request data from within a Flask app?

Upvotes: 3

Views: 2332

Answers (2)

Ricardo Boni
Ricardo Boni

Reputation: 1

The question is a bit outdated, but someone can get here as I did. =)

I've managed to do it, but for the whole app. So it becomes your responsibility to decode all data of the request, in all routes.

You can basically disable all encoding by setting the request charset to None. It can be done subclassing the werkzeug's BaseRequest class or simply:

application = Flask('api')
application.request_class.charset = None
[...]

This did the job for me.

Upvotes: 0

Josh Imhoff
Josh Imhoff

Reputation: 6946

After digging through the source for a little bit, I think I might be able to answer your question.

Flask's request object subclasses Werkzeug's request object and does a little bit of wrapping. After looking over Werkzeug's request object, it is obviously not the intention of the programmers to let you access the unparsed request object, but you might be able to do it anyway.

Recall that Flask and Werkzeug are WSGI-compatible. Therefore, you might be able to access the unparsed data like this:

Request.environ['wsgi.input']

The problem with this is you would have to manually seek the input stream yourself, which might prove difficult. Also, I think the Request object might process the stream and leave wsgi.input empty.

We need to subclass Flask's Request object:

class newRequest(Request):
    # here is the cool part!
    def _load_form_data(self):
        super(newRequest, self)._load_form_data()
        # stream is a local variable in Werkzeug's _load_form_data() method
        self.UNPARSED_STREAM = stream
        # now we should be able to access the request through Request.UNPARSED_STREAM

# now, we need to tell Flask to use our Request object
app.request_class = newRequest

Note that we are messing with class internals. This is a dangerous hack. I also have not tested this solution at all, but it seems like it should work to me.

Upvotes: 3

Related Questions