Skip to content

Commit e48ea7d

Browse files
Create get_ip_geolocation.py (#10902)
* Create get_ip_geolocation.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update get_ip_geolocation.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update get_ip_geolocation.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 1e50cf3 commit e48ea7d

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Diff for: web_programming/get_ip_geolocation.py

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import requests
2+
3+
4+
# Function to get geolocation data for an IP address
5+
def get_ip_geolocation(ip_address: str) -> str:
6+
try:
7+
# Construct the URL for the IP geolocation API
8+
url = f"https://ipinfo.io/{ip_address}/json"
9+
10+
# Send a GET request to the API
11+
response = requests.get(url)
12+
13+
# Check if the HTTP request was successful
14+
response.raise_for_status()
15+
16+
# Parse the response as JSON
17+
data = response.json()
18+
19+
# Check if city, region, and country information is available
20+
if "city" in data and "region" in data and "country" in data:
21+
location = f"Location: {data['city']}, {data['region']}, {data['country']}"
22+
else:
23+
location = "Location data not found."
24+
25+
return location
26+
except requests.exceptions.RequestException as e:
27+
# Handle network-related exceptions
28+
return f"Request error: {e}"
29+
except ValueError as e:
30+
# Handle JSON parsing errors
31+
return f"JSON parsing error: {e}"
32+
33+
34+
if __name__ == "__main__":
35+
# Prompt the user to enter an IP address
36+
ip_address = input("Enter an IP address: ")
37+
38+
# Get the geolocation data and print it
39+
location = get_ip_geolocation(ip_address)
40+
print(location)

0 commit comments

Comments
 (0)