Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call one Flask view from another one?

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

like image 233
Dan Abramov Avatar asked Jan 24 '14 19:01

Dan Abramov


People also ask

How do you call a function inside another Flask?

One of the easiest way is to use the sleep method(function) from the time package. import time def aFunction(): time. sleep(60) # Delay for 1 minute (60 seconds). Hope this solves your problem.

Can Flask handle multiple requests at once?

Yes, deploy your application on a different WSGI server, see the Flask deployment options documentation. The server component that comes with Flask is really only meant for when you are developing your application; even though it can be configured to handle concurrent requests with app.


Video Answer


1 Answers

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.

like image 51
Burnash Avatar answered Sep 29 '22 03:09

Burnash