python flasksqlalchemy重用函数多次返回结果

2024-04-29 07:06:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Flask中有两个函数和一个Route一起使用。我使用第一个函数的结果作为第二个函数的输入。但是,我想返回两个函数的结果,但是我只得到第二个函数的结果。如果我注释掉函数2(get\u net\u info()),那么函数1(get\u related\u interfaces())的结果将传递给render\u模板。你知道吗

如何返回这两个结果?(我的最终目标是将这两个结果返回到render\u 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

Tags: 函数infogetnetifistemplaterender
1条回答
网友
1楼 · 发布于 2024-04-29 07:06:16

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

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

我现在得到了上面的预期结果。非常感谢。你知道吗

相关问题 更多 >