Django ALLOWED

编程入门 行业动态 更新时间:2024-10-28 02:26:48
本文介绍了Django ALLOWED_HOSTS通过Apache接受本地IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我正在为Apache服务一个Django应用程序。 在Django的settings.py中,我有 DEBUG = False ,因此我不得不允许一些主机,如: ALLOWED_HOSTS = ['.dyndns ','localhost'] 。这样做很好,但是我想通过其内部IP地址在本地网络上访问服务器,如: 192.168.0.x 或 127.0.0.1 等等。我如何定义 192。* 或 127。* ALLOWED_HOSTS ,如果我想避免通过 ALLOWED_HOSTS = ['*'] ?

解决方案

根据@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 None

and setting ALLOWED_HOSTS = ['*'] in settings.py no longer opens up for all hosts in an uncontrolled way.

Thanks guys! :)

更多推荐

Django ALLOWED

本文发布于:2023-07-16 05:53:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1118559.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Django   ALLOWED

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!