changed speedtest service to ookla

This commit is contained in:
2026-03-10 03:37:02 +01:00
parent 90194076a6
commit 914f2ad2c9
7 changed files with 206 additions and 70 deletions

View File

@@ -1,16 +1,53 @@
from cfspeedtest import CloudflareSpeedtest
import subprocess
import json
import traceback
from db import init_db, insert_result
def run_test_and_save():
try:
tester = CloudflareSpeedtest()
results = tester.run_all(megabits=True) # returns SuiteResults
except Exception:
results = None # Trigger a failed test record
print("==== Running Ookla Speedtest ====")
init_db()
insert_result(results)
try:
# Corrected the typo in --accept-license
result = subprocess.run(
["speedtest", "--accept-license", "--accept-gdpr", "-f", "json"],
capture_output=True, text=True, check=True
)
# Ookla sometimes outputs logs and results in the same stream.
# We need to isolate the actual result JSON.
output_str = result.stdout.strip()
final_data = None
# Split by newline in case they are separated, or scan the string
for line in output_str.split('\n'):
if '{"type":"result"' in line:
# Isolate the valid JSON starting from {"type":"result"
start_idx = line.find('{"type":"result"')
valid_json_str = line[start_idx:]
try:
final_data = json.loads(valid_json_str)
break
except json.JSONDecodeError:
pass
if final_data and "download" in final_data:
insert_result(final_data)
print(f"Results successfully saved. Down: {final_data['download']['bandwidth'] * 8 / 1000000:.2f} Mbps")
else:
print("Could not find valid result JSON in output:", output_str)
insert_result(None)
except subprocess.CalledProcessError as e:
print("Speedtest failed execution:")
print("STDOUT:", e.stdout)
print("STDERR:", e.stderr)
insert_result(None)
except Exception as e:
print("Error processing results:")
print(traceback.format_exc())
insert_result(None)
print("==== Running Speedtest ====")
run_test_and_save()
print("==== Speedtest ended ====")
if __name__ == "__main__":
run_test_and_save()