How do I call one Flask view from another one?

僤鯓⒐⒋嵵緔 提交于 2020-01-12 04:52:11

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/21340678/how-do-i-call-one-flask-view-from-another-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!