martinbrose / cloudflarepycli

Python CLI and python class for retrieving user's realtime performance statistics
GNU General Public License v3.0
17 stars 4 forks source link

Problem with KeyError: 'region' on cfspeedtest #27

Open MrSaeid007 opened 1 month ago

MrSaeid007 commented 1 month ago

Hello guys, I am getting this error on my server. Can you help?

root@Iranserver:~# cfspeedtest Traceback (most recent call last): File "/usr/local/bin/cfspeedtest", line 8, in sys.exit(cfspeedtest()) File "/usr/local/lib/python3.10/dist-packages/cfspeedtest/main.py", line 39, in cfspeedtest results = CloudflareSpeedtest().run_all(megabits=not args.bps) File "/usr/local/lib/python3.10/dist-packages/cfspeedtest/cloudflare.py", line 212, in run_all meta = self.metadata() File "/usr/local/lib/python3.10/dist-packages/cfspeedtest/cloudflare.py", line 175, in metadata result_data["region"], KeyError: 'region'

root@Iranserver:~# python3 --version Python 3.10.12

root@IranServer:~# pip3 --version pip 22.0.2 from /usr/lib/python3/dist-packages/pip (python 3.10)

root@IranServer:~# cfspeedtest --debug Starting new HTTPS connection (1): speed.cloudflare.com:443 send: b'GET /meta HTTP/1.1\r\nHost: speed.cloudflare.com\r\nUser-Agent: python-requests/2.32 .3\r\nAccept-Encoding: gzip, deflate\r\nAccept: /\r\nConnection: keep-alive\r\n\r\n' reply: 'HTTP/1.1 200 OK\r\n' header: Date: Tue, 13 Aug 2024 17:30:28 GMT header: Content-Type: application/json header: Transfer-Encoding: chunked header: Connection: keep-alive header: Access-Control-Allow-Origin: * header: access-control-allow-credentials: true header: Report-To: {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v4?s=kyNupp uFXfFxktgSHhtnxykF%2FeZybgdfNwCl7bk9xtY%2B5ZsQsmgIpMdHv1J51LuZDZA2g6noj7b%2FrNa6QT6BeSF%2FVx 0jQDLlQaJtXihOnisO8p2hA1p6kSTq67RttDuW9476ZL4XJ4jNrqluaVXYw4JS"}],"group":"cf-nel","max_age" :604800} header: NEL: {"success_fraction":0.01,"report_to":"cf-nel","maxage":604800} header: Vary: Accept-Encoding header: Server-Timing: cfRequestDuration;dur=29.999971 header: Server: cloudflare header: CF-RAY: 8b2a6ee94b2c09af-ARN header: Content-Encoding: gzip header: server-timing: cfL4;desc="?proto=TCP&rtt=110362&sent=8&recv=8&lost=0&retrans=3&sent bytes=5786&recv_bytes=774&delivery_rate=10730&cwnd=38&unsent_bytes=0&cid=58ad46ab0f1bb7a5&ts =821&x=0" https://speed.cloudflare.com:443 "GET /meta HTTP/1.1" 200 None Traceback (most recent call last): File "/usr/local/bin/cfspeedtest", line 8, in sys.exit(cfspeedtest()) File "/usr/local/lib/python3.10/dist-packages/cfspeedtest/main.py", line 39, in cfspee dtest results = CloudflareSpeedtest().run_all(megabits=not args.bps) File "/usr/local/lib/python3.10/dist-packages/cfspeedtest/cloudflare.py", line 212, in run _all meta = self.metadata() File "/usr/local/lib/python3.10/dist-packages/cfspeedtest/cloudflare.py", line 175, in met adata result_data["region"], KeyError: 'region'

MrSaeid007 commented 1 month ago

Hi @tevslin @Nytelife26 @martinbrose

I fixed this error after modifying/usr/local/lib/python3.10/dist-packages/cfspeedtest/cloudflare.py with the specific below line:

def metadata(self) -> TestMetadata:
    """Retrieve test location code, IP address, ISP, city, and region."""
    result_data: dict[str, str] = self.request_sess.get(
        "https://speed.cloudflare.com/meta"
    ).json()
    return TestMetadata(
        result_data.get("clientIp", ""),
        result_data.get("asOrganization", ""),
        result_data.get("colo", ""),
        result_data.get("country", ""),  # Use 'country' if 'region' is missing
        result_data.get("country", "")   # Use 'country' as a fallback for 'city'
    )

And its worked. The KeyError: 'region' occurs because the region key is missing in the response. I did update the metadata method to handle the absence of this key. I request you to update it in the code.

Nytelife26 commented 1 month ago

The KeyError: 'region' occurs because the region key is missing in the response. I did update the metadata method to handle the absence of this key. I request you to update it in the code.

i was not aware this could happen, honestly. would you mind letting me know where in the world this issue occurs for? i have never been made aware of an instance where the region key is missing prior to this.

MrSaeid007 commented 1 month ago

The KeyError: 'region' occurs because the region key is missing in the response. I did update the metadata method to handle the absence of this key. I request you to update it in the code.

i was not aware this could happen, honestly. would you mind letting me know where in the world this issue occurs for? i have never been made aware of an instance where the region key is missing prior to this.

Hi @Nytelife26

This problem happened for Iran IPs that I tested who try to use the script. I'm not sure how many countries could be effected. but on my Germany server I don't have this problem.

I created a check_response.py script as below:

import requests

response = requests.get("https://speed.cloudflare.com/meta") print(response.json())

Then I ran it and I get this information(JSON Response):

{ 'hostname': 'speed.cloudflare.com', 'clientIp': '5.201.162.2', 'httpProtocol': 'HTTP/1.1', 'asn': 50810, 'asOrganization': 'Mobin Net Communication Company (Private Joint Sto', 'colo': 'ARN', 'country': 'IR', 'latitude': '35.69800', 'longitude': '51.41150' }

It seems that the region key is missing in the JSON response. So it better that you update the script. If you update the script the countries that had this issue will work on your script.