from flask import Flask, redirect, request, jsonify import requests import os import random # ... (Your existing code) app = Flask(__name__) def check_website_availability(url): try: response = requests.get(url) # 检查响应状态码,2xx表示成功 return response.status_code // 100 == 2 except requests.ConnectionError: return False @app.route('/', methods=['GET', 'POST']) def redirect_to_website(): if request.method == 'POST': # Process POST request and return a link url = os.getenv('OPENI_GRADIO_URL') server1 = 'https://mlunotebook.openi.org.cn' server2 = 'http://cloudbrain1notebook.openi.org.cn' url1 = server1 + url + "/" url2 = server2 + url + "/" options = [url1, f"{url1}sd2/", f"{url1}sd3/", f"{url1}sd4/"] selected_url = random.choices(options, weights=[0.25, 0.25, 0.25, 0.25])[0] options2 = [url2, f"{url2}sd2/", f"{url2}sd3/", f"{url2}sd4/"] selected_url2 = random.choices(options2, weights=[0.25, 0.25, 0.25, 0.25])[0] # Check if the URLs are accessible if check_website_availability(url1): return jsonify({"link": selected_url}) else: return jsonify({"link": selected_url2}) else: # Handle GET requests as before url = os.getenv('OPENI_GRADIO_URL') server1 = 'https://mlunotebook.openi.org.cn' server2 = 'http://cloudbrain1notebook.openi.org.cn' url1 = server1 + url + "/" url2 = server2 + url + "/" options = [f"{url1}sd1/", f"{url1}sd2/", f"{url1}sd3/", f"{url1}sd4/"] selected_url = random.choices(options, weights=[0.25, 0.25, 0.25, 0.25])[0] options2 = [f"{url1}sd1/", f"{url2}sd2/", f"{url2}sd3/", f"{url2}sd4/"] selected_url2 = random.choices(options2, weights=[0.25, 0.25, 0.25, 0.25])[0] if check_website_availability(url1): return redirect(selected_url) else: return redirect(selected_url2) if __name__ == '__main__': app.run(debug=False, port=5006)