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

如何让函数执行至满足条件后,将结果返回给调用它的函数?

修复递归创建目录时的返回值问题

原代码问题分析

原new函数在遇到目录已存在的FileExistsError时,递归调用自身但未返回递归结果,导致上层create_api()无法获取最终生成的ext值:

def new(url):
  html = (HTML hidden)
  ext = ''.join(random.choices(string.ascii_lowercase + string.digits, k=5))
  try:
    path = os.path.join(os.getcwd(), "templates/"+ext)
    os.mkdir(path)
  except FileExistsError:  
    new(url)  # 未返回递归调用的结果,导致上层拿不到返回值
  else:
    with open(f"{path}/index.html", "w") as f:
        f.write(html)
    return ext  

修复方案1:修正递归调用的返回值

只需在递归调用时添加return,让递归结果逐层向上传递:

def new(url):
  html = (HTML hidden)
  ext = ''.join(random.choices(string.ascii_lowercase + string.digits, k=5))
  try:
    path = os.path.join(os.getcwd(), "templates/"+ext)
    os.mkdir(path)
  except FileExistsError:  
    return new(url)  # 添加return,将递归结果返回给上层调用
  else:
    with open(f"{path}/index.html", "w") as f:
        f.write(html)
    return ext  

修复方案2:使用循环代替递归(更健壮)

递归存在栈溢出风险,极端情况下多次生成重复ext会触发递归深度错误。改用循环实现更可靠:

def new(url):
  html = (HTML hidden)
  while True:
    ext = ''.join(random.choices(string.ascii_lowercase + string.digits, k=5))
    path = os.path.join(os.getcwd(), "templates/"+ext)
    try:
      os.mkdir(path)
      # 目录创建成功后写入文件并返回结果
      with open(f"{path}/index.html", "w") as f:
          f.write(html)
      return ext
    except FileExistsError:
      # 目录已存在则跳过当前循环,重新生成ext重试
      continue

额外优化提示

  • 确保导入所需模块:import os, random, string, requests及Flask相关模块
  • request.environ['HTTP_REFERER']可能不存在,建议添加KeyError异常处理,避免程序崩溃
  • 循环版本彻底规避了递归深度限制问题,适合长期运行的服务场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 02:55:30