1

I'm creating a Flask app, in this part in my routes.py I want to get visitors' country and city from their IP with api.ipgeolocation.io, but get error urllib.error.HTTPError: HTTP Error 423: Locked

import json
from urllib.request import urlopen
from flask import request
...
public_ip = request.remote_addr
url = 'https://api.ipgeolocation.io/ipgeo?apiKey=API_KEY&ip={}'.format(public_ip)
response = urlopen(url)
data = json.load(response)
country = data['country_name']
city = data['city']

I test with fixed IP, ex. 8.8.8.8 it works.

url = 'https://api.ipgeolocation.io/ipgeo?apiKey=API_KEY&ip={}'.format("8.8.8.8")
>>>OUTPUT: United States, Mountain View

I don't know where am I wrong, any help would be greatly appreciated, thanks.

2 Answers2

1

I ran into the same response. For me the issue was that I was passing an internal IP. I ended up wrapping the call in a try catch and "ignoring" the internal IP's as they did not need to be included. HTH.

technified
  • 353
  • 1
  • 2
  • 15
0

If you're behind a web server (or load balancer), request.remote_addr will contain the internal IP address of the web server.

In that case you'll need to forward the client's external IP address from the web server.

For NGINX for example, you need to add something like the following inside a location block:

proxy_set_header X-Client-Address $remote_addr;

You can then read the value of X-Client-Address from the request header;

Benjineer
  • 1,530
  • 18
  • 22