From 30cae1a3843bbe590fb1ef113b70764bbde8b677 Mon Sep 17 00:00:00 2001 From: Rodrigo Verdiani Date: Sat, 8 Nov 2025 20:36:18 -0300 Subject: [PATCH] feat: implement request locking for SeleniumBase --- app.py | 44 ++++++++++++++++++++++++++++++++++++++++++++ flask_app.py | 35 ----------------------------------- 2 files changed, 44 insertions(+), 35 deletions(-) create mode 100644 app.py delete mode 100644 flask_app.py diff --git a/app.py b/app.py new file mode 100644 index 0000000..8d53996 --- /dev/null +++ b/app.py @@ -0,0 +1,44 @@ +import json +import time +import threading +from flask import Flask, request +from seleniumbase import SB + +rest_port = 8090 + +app = Flask(__name__) + +# Global lock to ensure only one SeleniumBase instance at a time +sb_lock = threading.Lock() + +@app.route("/url", methods=['POST']) +def process_url(): + data = request.get_json() + + if not data or 'url' not in data: + return json.dumps({"error": "URL parameter is required"}), 400 + + url = data['url'] + + # Try to acquire the lock + with sb_lock: + # Only one request at a time can enter this block + try: + with SB(uc=True, pls="none") as sb: + sb.activate_cdp_mode(url) + sb.sleep(5) + sb.uc_gui_click_captcha() + time.sleep(10) + + data = { + "page_source": sb.get_page_source() + } + + return json.dumps(data), 200, {'Content-Type': 'application/json'} + + except Exception as e: + return json.dumps({"error": str(e)}), 500 + +if __name__ == "__main__": + # Allow Flask to handle concurrent requests, but they'll queue on the lock + app.run(host='0.0.0.0', port=rest_port, threaded=True) diff --git a/flask_app.py b/flask_app.py deleted file mode 100644 index 146897e..0000000 --- a/flask_app.py +++ /dev/null @@ -1,35 +0,0 @@ -import json - -from flask import Flask, request -from seleniumbase import SB -import time - -rest_port = 8090 - -app = Flask(__name__) - -@app.route("/url", methods=['POST']) -def hello(): - data = request.get_json() - - if not data or 'url' not in data: - return json.dumps({"error": "URL parameter is required"}), 400 - - url = data['url'] - - with SB(uc=True) as sb: - sb.driver.page_load_strategy="eager" - sb.maximize_window() - sb.activate_cdp_mode(url) - sb.sleep(5) - sb.uc_gui_click_captcha() - time.sleep(10) - - data = { - "pageSource": sb.get_page_source() - } - - return json.dumps(data), 200, {'Content-Type': 'application/json'} - -if __name__ == "__main__": - app.run(host='0.0.0.0', port=rest_port)