python flask-sqlalchemy - 多次重用函数结果

时间:2018-04-15 19:35:34

标签: python python-3.x flask flask-sqlalchemy python-3.6

我在Flask中使用了Route中的两个函数。我使用第一个函数的结果作为第二个函数的输入。但是,我想返回两个函数的结果,但是,我只得到第二个函数的结果。如果我注释掉函数2(get_net_info()),函数1(get_related_interfaces())的结果将传递给render_template。

如何返回两者的结果? (我的最终目标是将两个结果都返回到render_template命令。)

功能1:

def get_related_interfaces(ipAddr):
    if ipAddr:
        try:
            queryInt = text("SELECT * FROM ROUTER_INTERFACES WHERE ROUTER_INTERFACE_DESCRIPTION LIKE :ipa")
            queryInt = queryInt.bindparams(ipa="%" + ipAddr + "%")
            interfaces = db.engine.execute(queryInt)

            return interfaces

    except Exception as e:
        print("IP Interfaces Error")
        print(e)

功能2:

def get_net_info(interfaces):
    if interfaces:
        try:
            for interface in interfaces:
                if interface.router_interface_ips:
                    candidateNet = ipaddress.IPv4Address(interface.router_interface_ips) + 1

                    return candidateNet

        except Exception as e:
            print("Net Detail Error")
            print(e)  

用法:

ipAddr = service_detail.ipAddr #192.168.0.1
interfaces = get_related_interfaces(ipAddr) #returns interfaces with ipAddr
candidateNet = get_net_info(interfaces) #returns candidateNet which is 192.168.0.2
print (candidateNet)

return render_template("service.html", interfaces=interfaces)

结果:

192.168.0.2 shows up in log(because of print statement) <-- This is what I wanted
interfaces is empty when returned to the template for rendering <-- Not what I want

预期结果:

192.168.0.2 shows up in the log
AND
interfaces result is returned to the template for rendering

1 个答案:

答案 0 :(得分:0)

基于@PRMoureu的建议,我在我的查询执行行的末尾添加了“fetchall()”,如下所示:

interfaces = db.engine.execute(queryInt).fetchall()

我现在正在获得上面的预期结果。谢谢。