简体   繁体   中英

How do I get django-debug-toolbar to only display on my ip address hosted on python anywhere?

I am trying to use django-debug-toolbar on python anywhere in a django app. It requires me to set my ip address in the settings which i've done, but the toolbar is not showing up. Upon further investigation I found that the django-debug-toolbar is looking for the REMOTE_ADDR attribute. The problem is that the REMOTE_ADDR attribute is not my ip address as normal. It would appear they're using a load balance or something, and so it doesn't actually give the IP that the request is coming from.

If I use the IP address from REMOTE_ADDR the toolbar displays, but it displays for EVERY user that goes to the site, not just me.

How can I get the IP address of the client making the request?

Python anywhere sets a custom definition in the headers called

HTTP_X_REAL_IP

This is the IP address from which pythonanywhere receives the request, and that seems to work best for getting the actual client IP.

You could also use HTTP_X_FORWARDED_FOR but in theory that could contain a set of different IP addresses if the incoming request went through some kind of proxy prior to getting to pythonAnywhere.

To do this, there are two options.

first, you can add this to your settings.py

def custom_show_toolbar(request.META.get('HTTP_X_REAL_IP', None) in INTERNAL_IPS):
    return True 
# Show toolbar, if the IP returned from HTTP_X_REAL_IP IS listed as INTERNAL_IPS in settings
    if request.is_ajax():
        return False
# Show toolbar, if the request is not ajax
    return bool(settings.DEBUG)
# show toolbar if debug is true

DEBUG_TOOLBAR_CONFIG = {
    'SHOW_TOOLBAR_CALLBACK': custom_show_toolbar,
}

Or you could modify the file middleware.py inside of the django-debug-toolbar folder, and changing the following code:

def show_toolbar(request):
    """
    Default function to determine whether to show the toolbar on a given page.
    """
    if request.META.get('REMOTE_ADDR', None) not in settings.INTERNAL_IPS:
        return False

    if request.is_ajax():
        return False

    return bool(settings.DEBUG)

To:

def show_toolbar(request):
    """
    Default function to determine whether to show the toolbar on a given page.
    """
    if request.META.get('HTTP_X_REAL_IP', None) not in settings.INTERNAL_IPS:
        return False

    if request.is_ajax():
        return False

    return bool(settings.DEBUG)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM