我如何从另一个瓶子中调用一个瓶子视图? [英] How do I call one Flask view from another one?

查看:190
本文介绍了我如何从另一个瓶子中调用一个瓶子视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个蓝图模块中有一个JSON API,而在另一个模块中有一个Web前端。

我想刮掉几个AJAX请求,客户端JS代码必须通过在前端视图模板中嵌入一些所需的JSON,然后将其发送到客户端,在这个要点上我发现了
$ b $ p如何从另一个Flask视图调用一个Flask视图?



我可以直接调用视图函数,但是 request 会对应于外部请求,这会混淆被调用的API函数。我已经使用 test_request_context 尝试了它几乎工作,但我不知道如何保持身份验证(我正在使用Flask登录)。

您可以使用 Flask测试客户端来执行此操作:

  client = app.test_client()
response = client.get('/ your / url',headers = list为了保持使用Flask-Login进行身份验证,您需要传递请求的头文件(header.jsp)。

感谢 Chris McKinnel 浏览相关问题


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

解决方案

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.

这篇关于我如何从另一个瓶子中调用一个瓶子视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆