Search code examples
pythonpython-3.xtastypie

Read IP address from api call in Tastypie?


In my code i want to know the ip address of the client from which the api call is made. Is there any way?

eg: Assume some guy initiated this api call like"http://server_url/api/v1/range/setup/"

In my api.py in server can i read the ip address of his machine ?


Solution

  • I once used this method, which should return IP address from your request meta data:

    def getClientIPaddress(request):
        http_x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if http_x_forwarded_for:
            ip_address = http_x_forwarded_for.split(',')[0]
        else:
            ip_address = request.META.get('REMOTE_ADDR')
        return ip_address
    

    Then you can call getClientIPaddress method from whereever you process your API call, eg:

    class YourResource(ModelResource):
        class Meta:
            #meta code here
    
        def obj_create(self, bundle, **kwargs):
            ip = getClientIPaddress(bundle.request)
            #your code here
    
        def obj_get_list(self, bundle, **kwargs):
            ip = getClientIPaddress(bundle.request)
            #your code here