简体   繁体   English

如何从AngularJS访问Flask全局?

[英]How can I access this Flask global from AngularJS?

I am building a internal web app with Flask that connects to various clusters. 我正在用Flask构建一个内部Web应用程序,该应用程序可以连接到各个集群。 95% of the URLs start with /cluster/cluster_name so I use the following code in my blueprints: 95%的URL以/ cluster / cluster_name开头,因此我在蓝图中使用以下代码:

cluster = Blueprint('cluster', __name__, url_prefix='/cluster/<cluster_name>')

@cluster.url_defaults
def add_cluster_name(endpoint, values):
    values.setdefault('cluster_name', g.cluster_name)

@cluster.url_value_preprocessor
def pull_cluster_name(endpoint, values):
    g.cluster_name = values.pop('cluster_name')

Which then allows me to use the following code to create a connection to the cluster before each request: 然后,它使我可以使用以下代码在每个请求之前创建与集群的连接:

@app.before_request
    def before_request():
        if not hasattr(g, 'manager'):
            g.manager = ClusterInterface(g.cluster_name)

This works perfectly and allows me to use {{ g.cluster_name }} in jinja2 templates. 这非常有效,可以让我在jinja2模板中使用{{g.cluster_name}}。

The problem is that I am moving to an AngularJS app for the frontend so I won't be using jinja2 templates/render_template() anymore. 问题是我要移到前端的AngularJS应用程序,所以我不再使用jinja2 templates / render_template()了。

So how can I have this global available to AngularJS templates without returning its value from every Flask views? 那么如何在不从每个Flask视图返回其值的情况下使AngularJS模板可以使用此全局变量呢?

Thank you. 谢谢。

Your views will now send JSON data instead of rendered HTML templates in order to communicate with Angular. 现在,您的视图将发送JSON数据而不是呈现的HTML模板,以便与Angular通信。 So make this data available in the JSON response. 因此,请在JSON响应中提供此数据。

return jsonify(cluster_name=g.cluster_name)

More likely, you should just send the default and available names when you first start the Angular app, and let it handle the value on it's end. 更有可能的是,您应该在首次启动Angular应用程序时发送默认名称和可用名称,并让它处理最后的值。

Sending g.manager is impossible, since it's a Python object with (probably) complex behavior, not something that is JSON serializable. 发送g.manager是不可能的,因为它是一个具有(可能)复杂行为的Python对象,而不是可序列化的JSON。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM