Python django.conf.settings.ALLOWED_HOSTS Examples

The following are 30 code examples of django.conf.settings.ALLOWED_HOSTS(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .
Example #1
Source File: utils.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def setup_test_environment():
    """Perform any global pre-test setup. This involves:

        - Installing the instrumented test renderer
        - Set the email backend to the locmem email backend.
        - Setting the active locale to match the LANGUAGE_CODE setting.
    """
    Template._original_render = Template._render
    Template._render = instrumented_test_render

    # Storing previous values in the settings module itself is problematic.
    # Store them in arbitrary (but related) modules instead. See #20636.

    mail._original_email_backend = settings.EMAIL_BACKEND
    settings.EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'

    request._original_allowed_hosts = settings.ALLOWED_HOSTS
    settings.ALLOWED_HOSTS = ['*']

    mail.outbox = []

    deactivate() 
Example #2
Source File: request.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def get_host(self):
        """Returns the HTTP host using the environment or request headers."""
        # We try three options, in order of decreasing preference.
        if settings.USE_X_FORWARDED_HOST and (
            'HTTP_X_FORWARDED_HOST' in self.META):
            host = self.META['HTTP_X_FORWARDED_HOST']
        elif 'HTTP_HOST' in self.META:
            host = self.META['HTTP_HOST']
        else:
            # Reconstruct the host using the algorithm from PEP 333.
            host = self.META['SERVER_NAME']
            server_port = str(self.META['SERVER_PORT'])
            if server_port != ('443' if self.is_secure() else '80'):
                host = '%s:%s' % (host, server_port)

        allowed_hosts = ['*'] if settings.DEBUG else settings.ALLOWED_HOSTS
        if validate_host(host, allowed_hosts):
            return host
        else:
            raise SuspiciousOperation(
                "Invalid HTTP_HOST header (you may need to set ALLOWED_HOSTS): %s" % host) 
Example #3
Source File: utils.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def setup_test_environment():
    """Perform any global pre-test setup. This involves:

        - Installing the instrumented test renderer
        - Set the email backend to the locmem email backend.
        - Setting the active locale to match the LANGUAGE_CODE setting.
    """
    Template._original_render = Template._render
    Template._render = instrumented_test_render

    # Storing previous values in the settings module itself is problematic.
    # Store them in arbitrary (but related) modules instead. See #20636.

    mail._original_email_backend = settings.EMAIL_BACKEND
    settings.EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'

    request._original_allowed_hosts = settings.ALLOWED_HOSTS
    settings.ALLOWED_HOSTS = ['*']

    mail.outbox = []

    deactivate() 
Example #4
Source File: utils.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def teardown_test_environment():
    """Perform any global post-test teardown. This involves:

        - Restoring the original test renderer
        - Restoring the email sending functions

    """
    Template._render = Template._original_render
    del Template._original_render

    settings.EMAIL_BACKEND = mail._original_email_backend
    del mail._original_email_backend

    settings.ALLOWED_HOSTS = request._original_allowed_hosts
    del request._original_allowed_hosts

    del mail.outbox 
Example #5
Source File: request.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def get_host(self):
        """Return the HTTP host using the environment or request headers."""
        host = self._get_raw_host()

        # There is no hostname validation when DEBUG=True
        if settings.DEBUG:
            return host

        domain, port = split_domain_port(host)
        if domain and validate_host(domain, settings.ALLOWED_HOSTS):
            return host
        else:
            msg = "Invalid HTTP_HOST header: %r." % host
            if domain:
                msg += " You may need to add %r to ALLOWED_HOSTS." % domain
            else:
                msg += " The domain name provided is not valid according to RFC 1034/1035."
            raise DisallowedHost(msg) 
Example #6
Source File: request.py    From python with Apache License 2.0 6 votes vote down vote up
def get_host(self):
        """Return the HTTP host using the environment or request headers."""
        host = self._get_raw_host()

        # Allow variants of localhost if ALLOWED_HOSTS is empty and DEBUG=True.
        allowed_hosts = settings.ALLOWED_HOSTS
        if settings.DEBUG and not allowed_hosts:
            allowed_hosts = ['localhost', '127.0.0.1', '[::1]']

        domain, port = split_domain_port(host)
        if domain and validate_host(domain, allowed_hosts):
            return host
        else:
            msg = "Invalid HTTP_HOST header: %r." % host
            if domain:
                msg += " You may need to add %r to ALLOWED_HOSTS." % domain
            else:
                msg += " The domain name provided is not valid according to RFC 1034/1035."
            raise DisallowedHost(msg) 
Example #7
Source File: utils.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def setup_test_environment():
    """Perform any global pre-test setup. This involves:

        - Installing the instrumented test renderer
        - Set the email backend to the locmem email backend.
        - Setting the active locale to match the LANGUAGE_CODE setting.
    """
    Template._original_render = Template._render
    Template._render = instrumented_test_render

    # Storing previous values in the settings module itself is problematic.
    # Store them in arbitrary (but related) modules instead. See #20636.

    mail._original_email_backend = settings.EMAIL_BACKEND
    settings.EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'

    request._original_allowed_hosts = settings.ALLOWED_HOSTS
    settings.ALLOWED_HOSTS = ['*']

    mail.outbox = []

    deactivate() 
Example #8
Source File: utils.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def teardown_test_environment():
    """Perform any global post-test teardown. This involves:

        - Restoring the original test renderer
        - Restoring the email sending functions
    """
    Template._render = Template._original_render
    del Template._original_render

    settings.EMAIL_BACKEND = mail._original_email_backend
    del mail._original_email_backend

    settings.ALLOWED_HOSTS = request._original_allowed_hosts
    del request._original_allowed_hosts

    del mail.outbox 
Example #9
Source File: request.py    From python2017 with MIT License 6 votes vote down vote up
def get_host(self):
        """Return the HTTP host using the environment or request headers."""
        host = self._get_raw_host()

        # Allow variants of localhost if ALLOWED_HOSTS is empty and DEBUG=True.
        allowed_hosts = settings.ALLOWED_HOSTS
        if settings.DEBUG and not allowed_hosts:
            allowed_hosts = ['localhost', '127.0.0.1', '[::1]']

        domain, port = split_domain_port(host)
        if domain and validate_host(domain, allowed_hosts):
            return host
        else:
            msg = "Invalid HTTP_HOST header: %r." % host
            if domain:
                msg += " You may need to add %r to ALLOWED_HOSTS." % domain
            else:
                msg += " The domain name provided is not valid according to RFC 1034/1035."
            raise DisallowedHost(msg) 
Example #10
Source File: request.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def get_host(self):
        """Return the HTTP host using the environment or request headers."""
        host = self._get_raw_host()

        # Allow variants of localhost if ALLOWED_HOSTS is empty and DEBUG=True.
        allowed_hosts = settings.ALLOWED_HOSTS
        if settings.DEBUG and not allowed_hosts:
            allowed_hosts = ['localhost', '127.0.0.1', '[::1]']

        domain, port = split_domain_port(host)
        if domain and validate_host(domain, allowed_hosts):
            return host
        else:
            msg = "Invalid HTTP_HOST header: %r." % host
            if domain:
                msg += " You may need to add %r to ALLOWED_HOSTS." % domain
            else:
                msg += " The domain name provided is not valid according to RFC 1034/1035."
            raise DisallowedHost(msg) 
Example #11
Source File: utils.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def teardown_test_environment():
    """Perform any global post-test teardown. This involves:

        - Restoring the original test renderer
        - Restoring the email sending functions

    """
    Template._render = Template._original_render
    del Template._original_render

    settings.EMAIL_BACKEND = mail._original_email_backend
    del mail._original_email_backend

    settings.ALLOWED_HOSTS = request._original_allowed_hosts
    del request._original_allowed_hosts

    del mail.outbox 
Example #12
Source File: request.py    From bioforum with MIT License 6 votes vote down vote up
def get_host(self):
        """Return the HTTP host using the environment or request headers."""
        host = self._get_raw_host()

        # Allow variants of localhost if ALLOWED_HOSTS is empty and DEBUG=True.
        allowed_hosts = settings.ALLOWED_HOSTS
        if settings.DEBUG and not allowed_hosts:
            allowed_hosts = ['localhost', '127.0.0.1', '[::1]']

        domain, port = split_domain_port(host)
        if domain and validate_host(domain, allowed_hosts):
            return host
        else:
            msg = "Invalid HTTP_HOST header: %r." % host
            if domain:
                msg += " You may need to add %r to ALLOWED_HOSTS." % domain
            else:
                msg += " The domain name provided is not valid according to RFC 1034/1035."
            raise DisallowedHost(msg) 
Example #13
Source File: domain.py    From pasportaservo with GNU Affero General Public License v3.0 6 votes vote down vote up
def domain(context, url=''):
    if 'request' in context:
        protocol = 'https' if context['request'].is_secure() else 'http'
        _domain = get_current_site(context['request']).domain
    elif 'protocol' in context and 'domain' in context:
        # Django emails
        protocol, _domain = context['protocol'], context['domain']
    elif 'site' in context:
        # Postman emails
        _domain = context['site'].domain
        protocol = 'https' if 'pasportaservo.org' in _domain else 'http'
    else:
        # Fallback
        if settings.DEBUG:
            protocol, _domain = 'http', 'localhost:8000'
        else:
            protocol, _domain = 'https', settings.ALLOWED_HOSTS[0]

    link = '{}://{}{}'.format(protocol, _domain, url)
    return link 
Example #14
Source File: utils.py    From python2017 with MIT License 5 votes vote down vote up
def setup_test_environment(debug=None):
    """
    Perform global pre-test setup, such as installing the instrumented template
    renderer and setting the email backend to the locmem email backend.
    """
    if hasattr(_TestState, 'saved_data'):
        # Executing this function twice would overwrite the saved values.
        raise RuntimeError(
            "setup_test_environment() was already called and can't be called "
            "again without first calling teardown_test_environment()."
        )

    if debug is None:
        debug = settings.DEBUG

    saved_data = SimpleNamespace()
    _TestState.saved_data = saved_data

    saved_data.allowed_hosts = settings.ALLOWED_HOSTS
    # Add the default host of the test client.
    settings.ALLOWED_HOSTS = list(settings.ALLOWED_HOSTS) + ['testserver']

    saved_data.debug = settings.DEBUG
    settings.DEBUG = debug

    saved_data.email_backend = settings.EMAIL_BACKEND
    settings.EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'

    saved_data.template_render = Template._render
    Template._render = instrumented_test_render

    mail.outbox = []

    deactivate() 
Example #15
Source File: gen_commands.py    From tethys with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def gen_nginx(args):
    hostname = str(settings.ALLOWED_HOSTS[0]) if len(settings.ALLOWED_HOSTS) > 0 else '127.0.0.1'
    workspaces_root = get_settings_value('TETHYS_WORKSPACES_ROOT')
    static_root = get_settings_value('STATIC_ROOT')

    context = {
        'hostname': hostname,
        'workspaces_root': workspaces_root,
        'static_root': static_root,
        'client_max_body_size': args.client_max_body_size,
        'port': args.tethys_port
    }
    return context 
Example #16
Source File: request.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def get_host(self):
        """Returns the HTTP host using the environment or request headers."""
        # We try three options, in order of decreasing preference.
        if settings.USE_X_FORWARDED_HOST and (
                'HTTP_X_FORWARDED_HOST' in self.META):
            host = self.META['HTTP_X_FORWARDED_HOST']
        elif 'HTTP_HOST' in self.META:
            host = self.META['HTTP_HOST']
        else:
            # Reconstruct the host using the algorithm from PEP 333.
            host = self.META['SERVER_NAME']
            server_port = str(self.META['SERVER_PORT'])
            if server_port != ('443' if self.is_secure() else '80'):
                host = '%s:%s' % (host, server_port)

        # There is no hostname validation when DEBUG=True
        if settings.DEBUG:
            return host

        domain, port = split_domain_port(host)
        if domain and validate_host(domain, settings.ALLOWED_HOSTS):
            return host
        else:
            msg = "Invalid HTTP_HOST header: %r." % host
            if domain:
                msg += " You may need to add %r to ALLOWED_HOSTS." % domain
            else:
                msg += " The domain name provided is not valid according to RFC 1034/1035."
            raise DisallowedHost(msg) 
Example #17
Source File: mixins.py    From connect with MIT License 5 votes vote down vote up
def _cleanse_tags(self, message):
        """Using BeautifulSoup and bleach, remove or modify bad tags & attrs"""
        bleached_message = bleach.clean(
            message,
            tags=self.VALID_TAGS,
            attributes=self.VALID_ATTRS,
            protocols=self.VALID_SCHEMES,
            strip=True)

        soup = BeautifulSoup(bleached_message, "lxml")

        # Find all the tags in the HTML code
        for tag in soup.findAll():
            # We have to remove any invalid tags created by `lxml`, like <html>
            # and <body>
            if tag.name not in self.VALID_TAGS:
                tag.hidden = True

            for attr, value in dict(tag.attrs).iteritems():
                # Make sure any src attributes are on an allowed domain
                if attr == 'src':
                    parsed_src = urlparse(value)
                    valid_netlocs = settings.ALLOWED_HOSTS
                    valid_netlocs.append('')
                    if parsed_src.netloc not in valid_netlocs:
                        tag.hidden = True

            # All image tags should have a max-width style attribute to ensure
            # they always fit inside any template or email client they're
            # inserted into.
            if self.ADD_MAX_WIDTH and tag.name == 'img':
                tag.attrs['style'] = 'max-width: 100%;'

        # Grab the HTML from BeautifulSoup, return it in UTF8
        return unicode(soup).encode("utf-8", errors="ignore") 
Example #18
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_allowed_hosts(self):
        for type_ in (list, tuple):
            with self.subTest(type_=type_):
                allowed_hosts = type_('*')
                with mock.patch('django.test.utils._TestState') as x:
                    del x.saved_data
                    with self.settings(ALLOWED_HOSTS=allowed_hosts):
                        setup_test_environment()
                        self.assertEqual(settings.ALLOWED_HOSTS, ['*', 'testserver']) 
Example #19
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_empty_allowed_hosts_error(self):
        out, err = self.run_manage(['runserver'])
        self.assertNoOutput(out)
        self.assertOutput(err, 'CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False.') 
Example #20
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.write_settings('settings.py', sdict={
            'ALLOWED_HOSTS': [],
            'DEBUG': False,
        }) 
Example #21
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_allowed_hosts(self):
        for type_ in (list, tuple):
            with self.subTest(type_=type_):
                allowed_hosts = type_('*')
                with mock.patch('django.test.utils._TestState') as x:
                    del x.saved_data
                    with self.settings(ALLOWED_HOSTS=allowed_hosts):
                        setup_test_environment()
                        self.assertEqual(settings.ALLOWED_HOSTS, ['*', 'testserver']) 
Example #22
Source File: utils.py    From python2017 with MIT License 5 votes vote down vote up
def teardown_test_environment():
    """
    Perform any global post-test teardown, such as restoring the original
    template renderer and restoring the email sending functions.
    """
    saved_data = _TestState.saved_data

    settings.ALLOWED_HOSTS = saved_data.allowed_hosts
    settings.DEBUG = saved_data.debug
    settings.EMAIL_BACKEND = saved_data.email_backend
    Template._render = saved_data.template_render

    del _TestState.saved_data
    del mail.outbox 
Example #23
Source File: testcases.py    From python2017 with MIT License 5 votes vote down vote up
def setUpClass(cls):
        super(LiveServerTestCase, cls).setUpClass()
        connections_override = {}
        for conn in connections.all():
            # If using in-memory sqlite databases, pass the connections to
            # the server thread.
            if conn.vendor == 'sqlite' and conn.is_in_memory_db():
                # Explicitly enable thread-shareability for this connection
                conn.allow_thread_sharing = True
                connections_override[conn.alias] = conn

        cls._live_server_modified_settings = modify_settings(
            ALLOWED_HOSTS={'append': cls.host},
        )
        cls._live_server_modified_settings.enable()
        cls.server_thread = cls._create_server_thread(connections_override)
        cls.server_thread.daemon = True
        cls.server_thread.start()

        # Wait for the live server to be ready
        cls.server_thread.is_ready.wait()
        if cls.server_thread.error:
            # Clean up behind ourselves, since tearDownClass won't get called in
            # case of errors.
            cls._tearDownClassInternal()
            raise cls.server_thread.error 
Example #24
Source File: tests.py    From govready-q with GNU General Public License v3.0 5 votes vote down vote up
def setUpClass(cls):
        super(SeleniumTest, cls).setUpClass()

        # Override the email backend so that we can capture sent emails.
        from django.conf import settings
        settings.EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'

        # Override ALLOWED_HOSTS, SITE_ROOT_URL, etc.
        # because they may not be set or set properly in the local environment's
        # non-test settings for the URL assigned by the LiveServerTestCase server.
        settings.ALLOWED_HOSTS = ['localhost', 'testserver']
        settings.SITE_ROOT_URL = cls.live_server_url

        # In order for these tests to succeed when not connected to the
        # Internet, disable email deliverability checks which query DNS.
        settings.VALIDATE_EMAIL_DELIVERABILITY = False

        ## Turn on DEBUG so we can see errors better.
        #settings.DEBUG = True

        # Start a headless browser.
        import selenium.webdriver
        from selenium.webdriver.chrome.options import Options as ChromeOptions
        options = selenium.webdriver.ChromeOptions()
        if SeleniumTest.window_geometry == "maximized":
            options.add_argument("--start-maximized") # too small screens make clicking some things difficult
        else:
            options.add_argument("--window-size=" + ",".join(str(dim) for dim in SeleniumTest.window_geometry))
        cls.browser = selenium.webdriver.Chrome(chrome_options=options)
        cls.browser.implicitly_wait(3) # seconds

        # Clean up and quit tests if Q is in SSO mode
        if getattr(settings, 'PROXY_HEADER_AUTHENTICATION_HEADERS', None):
            print("Cannot run tests.")
            print("Tests will not run when IAM Proxy enabled (e.g., when `local/environment.json` sets `trust-user-authentication-headers` parameter.)")
            cls.browser.quit()
            super(SeleniumTest, cls).tearDownClass()
            exit() 
Example #25
Source File: cases.py    From django-pgschemas with MIT License 5 votes vote down vote up
def add_allowed_test_domain(cls):
        cls.BACKUP_ALLOWED_HOSTS = settings.ALLOWED_HOSTS
        # ALLOWED_HOSTS is a special setting of Django setup_test_environment so we can't modify it with helpers
        if ALLOWED_TEST_DOMAIN not in settings.ALLOWED_HOSTS:
            settings.ALLOWED_HOSTS += [ALLOWED_TEST_DOMAIN] 
Example #26
Source File: cases.py    From django-pgschemas with MIT License 5 votes vote down vote up
def remove_allowed_test_domain(cls):
        settings.ALLOWED_HOSTS = cls.BACKUP_ALLOWED_HOSTS 
Example #27
Source File: views.py    From TWLight with MIT License 5 votes vote down vote up
def _set_return_url(self, referer):
        # We'll validate the return_url set in the previous method
        return_url = reverse("users:home")  # default
        domain = urlparse(referer).netloc
        if domain in settings.ALLOWED_HOSTS:
            return_url = referer
        return return_url 
Example #28
Source File: conftest.py    From micromasters with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def override_allowed_hosts(settings):
    """
    Override ALLOWED_HOSTS to force Django to allow outside connections to the selenium test server
    """
    settings.ALLOWED_HOSTS = "['*']" 
Example #29
Source File: views.py    From MultiExplorer with MIT License 5 votes vote down vote up
def api_docs(request):
    return TemplateResponse(request, 'api_docs.html', {
        'service_table': service_table_html,
        'domain': settings.ALLOWED_HOSTS[0],
    }) 
Example #30
Source File: runserver.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def handle(self, *args, **options):
        from django.conf import settings

        if not settings.DEBUG and not settings.ALLOWED_HOSTS:
            raise CommandError('You must set settings.ALLOWED_HOSTS if DEBUG is False.')

        self.use_ipv6 = options.get('use_ipv6')
        if self.use_ipv6 and not socket.has_ipv6:
            raise CommandError('Your Python does not support IPv6.')
        self._raw_ipv6 = False
        if not options.get('addrport'):
            self.addr = ''
            self.port = DEFAULT_PORT
        else:
            m = re.match(naiveip_re, options['addrport'])
            if m is None:
                raise CommandError('"%s" is not a valid port number '
                                   'or address:port pair.' % options['addrport'])
            self.addr, _ipv4, _ipv6, _fqdn, self.port = m.groups()
            if not self.port.isdigit():
                raise CommandError("%r is not a valid port number." % self.port)
            if self.addr:
                if _ipv6:
                    self.addr = self.addr[1:-1]
                    self.use_ipv6 = True
                    self._raw_ipv6 = True
                elif self.use_ipv6 and not _fqdn:
                    raise CommandError('"%s" is not a valid IPv6 address.' % self.addr)
        if not self.addr:
            self.addr = '::1' if self.use_ipv6 else '127.0.0.1'
            self._raw_ipv6 = bool(self.use_ipv6)
        self.run(**options)