You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python文件其他位置使用Flask接口返回的字典值?

解决Flask接口内字典在外部复用的问题

方案1:将字典定义为全局变量

把thisDictionary提到函数外部作为全局变量,在接口函数内声明使用全局变量,这样外部代码就能直接引用。但要注意多请求并发场景下会存在数据覆盖的风险。

from flask import Flask, request

application = Flask(__name__)
# 定义全局字典
thisDictionary = {}

@application.route('/calculate', methods=['POST'])
def itemadd():
    global thisDictionary  # 声明使用全局变量
    body = request.get_json()
    total = str(getAnswer("payload","6148ece5989a301f24ee9934")) 
    thisDictionary["value"] = total
    return thisDictionary

# 在其他地方使用时建议用copy,避免后续修改影响新字典
newDictionary = thisDictionary.copy()

if __name__ == '__main__':
    application.run(host='0.0.0.0')

方案2:提取生成逻辑为独立函数

把生成字典的代码抽成单独函数,接口和其他需要的地方都调用这个函数,各自生成独立的字典实例,避免并发冲突。

如果生成逻辑依赖请求数据,确保函数在请求上下文内调用:

from flask import Flask, request

application = Flask(__name__)

def generate_result_dict():
    body = request.get_json()
    total = str(getAnswer("payload","6148ece5989a301f24ee9934")) 
    return {"value": total}

@application.route('/calculate', methods=['POST'])
def itemadd():
    thisDictionary = generate_result_dict()
    return thisDictionary

# 在其他请求上下文内的函数中使用
def other_request_handler():
    newDictionary = generate_result_dict()
    # 处理逻辑

如果其他代码不在请求上下文里,调整函数让参数可传入:

def generate_result_dict(target_param):
    total = str(getAnswer(target_param,"6148ece5989a301f24ee9934")) 
    return {"value": total}

@application.route('/calculate', methods=['POST'])
def itemadd():
    thisDictionary = generate_result_dict("payload")
    return thisDictionary

# 非请求场景直接调用
newDictionary = generate_result_dict("payload")

方案3:用缓存存储(跨请求复用场景)

如果需要字典内容在多个请求间共享,可以用内存缓存或Flask缓存扩展,注意多线程环境下要加锁避免数据竞争。

from flask import Flask, request

application = Flask(__name__)
# 内存缓存容器
cache_store = {}

@application.route('/calculate', methods=['POST'])
def itemadd():
    body = request.get_json()
    total = str(getAnswer("payload","6148ece5989a301f24ee9934")) 
    thisDictionary = {"value": total}
    cache_store["calculation_result"] = thisDictionary
    return thisDictionary

# 其他地方获取缓存的字典
newDictionary = cache_store.get("calculation_result", {})

if __name__ == '__main__':
    application.run(host='0.0.0.0')

内容的提问来源于stack exchange,提问作者YSH 222

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 02:18:19