根据@rnevius的建议,并根据@AlvaroAV在如何在django中设置自定义中间件,我已经设法解决这个中间件:
从django.http导入H pre $ p class FilterHostMiddleware(object) def process_request(self,request): allowed_hosts = ['127.0.0.1','localhost']#在此指定完整的主机名 ho st = request.META.get('HTTP_HOST') 如果主机[len(主机)-10:] =='dyndns':#如果主机以dyndns结尾然后添加允许的主机 allowed_hosts.append(host) elif host [:7] =='192.168':#如果主机从192.168开始,然后添加到允许的主机 allowed_hosts.append (主机) 如果主机不在allowed_hosts中: raise HttpResponseForbidden 返回无并在 settings.py 不再以不受控制的方式打开所有主机。
谢谢你们! :)
I'm serving a Django app with Apache. In Django's settings.py I have DEBUG = False, therefore I had to allow some hosts, like: ALLOWED_HOSTS = ['.dyndns', 'localhost']. This works fine, however I would like to have the server accessible on the local network via its internal IP address as well, like: 192.168.0.x, or 127.0.0.1, etc. How could I define 192.* or 127.* in ALLOWED_HOSTS, if I'd like to avoid opening up the access entirely by ALLOWED_HOSTS = ['*']?
解决方案Following the recommendation from @rnevius, and based on the guidelines from @AlvaroAV in how to setup custom middleware in django, I've managed to solve with this middleware:
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': # if the host ends with dyndns 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 Noneand setting ALLOWED_HOSTS = ['*'] in settings.py no longer opens up for all hosts in an uncontrolled way.
Thanks guys! :)
更多推荐
Django ALLOWED
发布评论