Very simple ClientInfo example

Howdy,

I just want to share a simple example of how to get and use information when a client connects to your app.

https://anvil.works/build#clone:UPVFD5WWFUJ7Q5ZR=OPYBGX6OWJOAPUABHSDQ2UYZ

In the example we define a server side function (callable) which parses the anvil.server.context.client object.

@anvil.server.callable
def check_client_info():
    client_info = anvil.server.context.client # returns client info object
    
    type = client_info.type
    ip = client_info.ip
    country = client_info.location.country
    country_code = client_info.location.country_code
    city = client_info.location.city
    subdivision = client_info.location.subdivision
    longitude = client_info.location.longitude
    latitude = client_info.location.latitude

    # in this example we are only interested in the country
    return country

When the form is initialized e.g. when a client connects, we call the server side function check_client_info. In this example, the form will only load if the client is located in Sweden.

class Form1(Form1Template):

    def __init__(self, **properties):
        resp = anvil.server.call('check_client_info')

        while resp != "Sweden":
            alert("This app is only allowed in Sweden")

        self.label_1.text = f"You connected to the app from {resp}"
        
        # Set Form properties and Data Bindings.
        self.init_components(**properties)

Happy hacking :slight_smile:

7 Likes