Question

I have a JSON API in one blueprint module, and a web frontend in another one.

I would like to shave off a few AJAX requests the client JS code would have to make by embedding some of the JSON it'll need in the frontend view template, before sending it to the client, like in this gist I found.

How do I call one Flask view from another Flask view?

I could have called the view function directly, but request would correspond to the “outer” request, and this confuses the called API function. I've tried using test_request_context and it almost works but I can't figure out how to keep the authentication (I'm using Flask-Login).

Was it helpful?

Solution

You can use a Flask test client for this:

client = app.test_client()
response = client.get('/your/url', headers=list(request.headers))

To keep the authentication with Flask-Login you need to pass your request's headers.

Thanks to Chris McKinnel for answering a related question.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top