13

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).

2
  • 2
    I would take the logic that you are using to retrieve the data from the AJAX-called view and put it into another function. This function should not rely on authentication. Then, call that function from both views. Commented Jan 24, 2014 at 21:14
  • @Mark: That's what I'd normally have done, but the JSON functions rely on request object for generating pagination URLs and a few other things. I don't want to rewrite them all to explicitly pass endpoint, request.args, etc. I also need this pagination info in the generated JSON so the client knows how to fetch the next page. I agree it's not the most elegant solution, but it works best for me. Commented Jan 24, 2014 at 21:37

1 Answer 1

23

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.

1
  • 3
    worked like a charm! Also you could use from flask import current_app and use current_app.test_client()
    – deeshank
    Commented Apr 19, 2017 at 19:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.