适用于Amazon ELB的Django ALLOWED_HOSTS [英] Django ALLOWED_HOSTS for Amazon ELB

查看:76
本文介绍了适用于Amazon ELB的Django ALLOWED_HOSTS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是Django,并且我具有ALLOWED_HOSTS设置,其中包括我的EC2的私有IP,如下所示:

I'm using Django and I have the ALLOWED_HOSTS setting to include my EC2's private IP as per below:

import requests
EC2_PRIVATE_IP = None
try:
    EC2_PRIVATE_IP = requests.get('http://169.254.169.254/latest/meta-data/local-ipv4', timeout=0.01).text
except requests.exceptions.RequestException:
    pass
if EC2_PRIVATE_IP and not DEBUG:
    ALLOWED_HOSTS.append(EC2_PRIVATE_IP)

问题是上述内容未考虑将请求转发到我的EC2实例的ELB.有没有办法以编程方式使其工作?我可以请求公共IP地址还是可以设置检查DNS?

Problem is that the above does not take into consideration the ELB's that forward the request to my EC2 instances. Is there a way to make that work programmatically? Can I request the public IP address or have setting to check the DNS instead?

我看到了ELB的公共IP地址的问题.

I'm seeing this issue with the ELB's public IP address.

推荐答案

另一个简单的解决方案是编写自定义MIDDLEWARE,它将在检查ALLOWED_HOSTS之前将响应发送给ELB.因此,现在您不必动态加载ALLOWED_HOSTS.

Another simple solution would be to write a custom MIDDLEWARE which will give the response to ELB before the ALLOWED_HOSTS is checked. So now you don't have to load ALLOWED_HOSTS dynamically.

中间件可以很简单:

project/app/middleware.py

from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin

class HealthCheckMiddleware(MiddlewareMixin):
    def process_request(self, request):
        if request.META["PATH_INFO"] == "/ping/":
            return HttpResponse("pong")

settings.py

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'app.middleware.HealthCheckMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    ...
]

Django中间件参考 https://docs.djangoproject.com/en/dev/topics/http/middleware/

Django Middleware reference https://docs.djangoproject.com/en/dev/topics/http/middleware/

这篇关于适用于Amazon ELB的Django ALLOWED_HOSTS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆