我的代码
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
@app.route('/create-api')
def create_api():
if "(URL hidden)/create" == request.environ['HTTP_REFERER']:
args = request.args
try:
url = args.get('url')
except:
return redirect(url_for('home', error_msg="No URL provided."))
else:
r = requests.get(url)
if r.status_code != 200:
return redirect(url_for('home', error_msg="Not a valid URL."))
else:
ext = new(url)
return redirect(url_for('home', url=f"(URL hidden)/{ext}"))
else:
print("NOPE")
return 401
此代码不起作用,因为该函数是在同一个函数内部调用的,导致它不会向create_api()
返回任何内容。
我想要的是继续尝试创建目录,直到有一个可用,然后返回create_api()
函数。
您需要递归地将函数return
传递给它自己,以便实际使用函数的返回值:
except FileExistsError:
return new(url)
根据此函数将运行的次数以及将生成的唯一目录名的数量,您可能希望为max_tries=0
或其他内容包含一个新的可选参数,以防止堆栈溢出。