What I’m trying to do:
I am trying to test localization settings in my app using a VPN to access the app from different countries.
What I’ve tried and what’s not working:
With the VPN in place, my IP address correclty shows me in e.g. Sweden, but a server side call of
anvil.server.context.client.location.country_code
returns “NZ” instead.
Are you running it in the same tab as the IDE? Try running it in another tab with the VPN on, that usually runs more purely than the IDE.
It is not related to the IDE. In another tab, even in another browser, anvil.server.context.client.location.country_code gives me (albeit quite consistently) NZ when whatmyipaddress.com shows correctly Sweden.
Doing some web searching, it looks like the country code reported by the browser isn’t always based on the IP address. Apparently it sometimes uses geolocation? Try turning off geolocation in your browser and try it again, and see if it still reports NZ. That’ll at least narrow down if that’s the issue.
2 Likes
Even with geolocation off, whatsmyipaddress shows correctly Sweden while anvil.server.context.client.location.country_code returns NZ.
I took a closer look at what anvil.server.context.client returns, and the ip address it gives is indeed correct - checking it evaluates to Sweden, as it should be, but the location deduced from that ip is incorrect:
{‘type’: ‘browser’, ‘ip’: ‘130.195.218.20’, ‘location’: {‘city’: ‘Wellington’, ‘subdivision’: ‘Wellington’, ‘latitude’: -41.286, ‘longitude’: 174.7719, ‘country_code’: ‘NZ’, ‘country’: ‘New Zealand’}}
(I used the serialization routine suggested in another thread to log the contents.)
Hope that helps in narrowing down the issue.
After a lot of digging I found a workaround.
What works: call e.g. ipapi.co on the client side
import anvil.http
try:
data = anvil.http.request("https://ipapi.co/json/", json=True)
client_country = data.get("country_code")
except:
client_country = None
Then pass the country code to the server if needed.
What does not work: anvil.server.context.client.location on the server side. It provides seemingly random results that show a remarkable stickiness. The results seem to have no correlation to what the client ip adress actually is, and they change only when I restart the computer. Testing with separate windows and another computer, the location returned by anvil.server.context.client.location never changes on a computer even as I switch location via VPN, switch browser, or go incognito. Testing on another computer, I get another location (this time in Czechia), but it remains the anvil.server.context.client.location until I reboot the computer, after which I get a location in the US although my VPN has me in Belgium and client side correctly detects that. As far as I can tell, anvil.server.context.client.ip is correct.
1 Like