Django ALLOWED_HOSTS IPs range

前端 未结 5 1794
醉梦人生
醉梦人生 2021-01-31 08:46

Is there a way to set a range of ALLOWED_HOSTS IPs in django?

Something like this:

ALLOWED_HOSTS = [\'172.17.*.*\']
5条回答
  •  天命终不由人
    2021-01-31 09:44

    I've found such solution for filtering range of IPs:

    https://stackoverflow.com/a/36222755/3766751

    Using this approach we can filter IPs by any means (f.e. with regex).

    from django.http import HttpResponseForbidden
    
    class FilterHostMiddleware(object):
    
        def process_request(self, request):
    
            allowed_hosts = ['127.0.0.1', 'localhost']  # specify complete host names here
            host = request.META.get('HTTP_HOST')
    
            if host[len(host)-10:] == 'dyndns.org':  # if the host ends with dyndns.org then add to the allowed hosts
                allowed_hosts.append(host)
            elif host[:7] == '192.168':  # if the host starts with 192.168 then add to the allowed hosts
                allowed_hosts.append(host)
    
            if host not in allowed_hosts:
                raise HttpResponseForbidden
    
            return None
    

    Thanks for @Zorgmorduk

提交回复
热议问题