diff --git a/server.py b/server.py index 7061776..e4a3020 100644 --- a/server.py +++ b/server.py @@ -12,6 +12,9 @@ monkey.patch_all() app = Flask(__name__) A1 = "" +# 确保在模块级别声明全局变量 +browser_context = None +context_page = None def get_context_page(instance, stealth_js_path): @@ -42,25 +45,25 @@ print("跳转小红书首页成功,等待调用") def sign(uri, data, a1, web_session): - try: - # Ensure the page is still valid and reload if necessary - if context_page.is_closed(): - global browser_context, context_page - browser_context, context_page = get_context_page(playwright, stealth_js_path) - context_page.goto("https://www.xiaohongshu.com") - time.sleep(5) - context_page.reload() - time.sleep(1) + global browser_context, context_page # 声明全局变量 + try: + # 确保页面仍然有效,如果页面已关闭则重新初始化 + if context_page is None or context_page.is_closed(): + browser_context, context_page = get_context_page(playwright, stealth_js_path) + context_page.goto("https://www.xiaohongshu.com") + time.sleep(5) + context_page.reload() + time.sleep(1) - # Evaluate the JavaScript function - encrypt_params = context_page.evaluate("([url, data]) => window._webmsxyw(url, data)", [uri, data]) - return { - "x-s": encrypt_params["X-s"], - "x-t": str(encrypt_params["X-t"]) - } - except Exception as e: - print(f"Error during sign operation: {e}") - return {"error": str(e)} + # 执行 JavaScript 函数 + encrypt_params = context_page.evaluate("([url, data]) => window._webmsxyw(url, data)", [uri, data]) + return { + "x-s": encrypt_params["X-s"], + "x-t": str(encrypt_params["X-t"]) + } + except Exception as e: + print(f"Error during sign operation: {e}") + return {"error": str(e)} @app.route("/sign", methods=["POST"])