Forums

400 Client Error: Bad Request for url - Trying to locate IP

I'm trying to locate the visitor IP address using the following: https://github.com/ipinfo/python

I'm doing the exact same thing as in the documentation and I got the access_token:

import ipinfo

if request.environ.get('HTTP_X_FORWARDED_FOR') is None:
        ip_address = request.environ['REMOTE_ADDR']
else:
        ip_address = request.environ['HTTP_X_FORWARDED_FOR']

handler = ipinfo.getHandler(mytoken)
details = handler.getDetails(ip_address)

However the last lines give me:

400 Client Error: Bad Request for url: https://ipinfo.io/2.44.94.227

It returns this error with every IP address. Do you have any ideas? Thanks!

Check out this help page for instructions on how to get the real IP of a web request on PythonAnywhere.

Thank you. However, this wasn't an IP-related problem, as it gives the same error for every IPs. I think that request is not whitelisted, am I wrong?

Yes, it's whitelisted -- you can see the whitelist here. Also, a whitelist error would show up as a 403 (forbidden) error rather than a 400 (bad request).

The error that you're seeing means that the server at ipinfo.io has received the request but has deemed it malformed in some way. If it's not providing any further information, you might want to try accessing it directly (using, say, the requests library) in order to work out why it's rejecting your specific queries.

I solved using the requests library. Thank you very much!

Glad to hear that!