allowed_host changes not effective - django

I've got an address say example.com and have added it to the allowed_hosts list. But when I access the site I get
ALLOWED_HOSTS ['127.0.0.1', '::1', '178.XX.XX.XXX', 'xx80::xx81:xxx:xx3x:x12x%eth0']
in the debug error page, while the actual settings.py file reads ['178.XX.XX.XXX','example.com']. I figured the changes to settings.py aren't registered as I can remove 178.XX.XX.XXX from the list and still access the site (after clearing the browser cache) I've restarted nginx, gunicorn and the whole server to no avail. The whole thing is set up on ubuntu 16.04 running django 1.8 and using nginx and gunicorn. Any ideas where this override of allowed_hosts could be coming from?

Ok this is embarassing but the One-cick install for django on 16.04 from Digital Ocean adds a line at the very end of settings.py where ALLOWED_HOSTS is redefined.
# Find out what the IP addresses are at run time
# This is necessary because otherwise Gunicorn will reject the connections
def ip_addresses():
ip_list = []
for interface in netifaces.interfaces():
addrs = netifaces.ifaddresses(interface)
for x in (netifaces.AF_INET, netifaces.AF_INET6):
if x in addrs:
ip_list.append(addrs[x][0]['addr'])
return ip_list
# Discover our IP address
ALLOWED_HOSTS = ip_addresses()
ALLOWED_HOSTS.append('.example.com') #I added this line
So adding an append to the line fixes the problem.

Related

Dotenv Doesn't Handle Multiple Hosts in ALLOWED_HOSTS

In my production setting.py file I have:
from dotenv import load_dotenv
load_dotenv(override=True)
DEBUG = os.getenv('DEBUG')
#ALLOWED_HOSTS = os.getenv("ALLOWED_HOSTS")
ALLOWED_HOSTS = ['example.com', 'www.example.com']
In my .env file in production, I have
DEBUG=False
ALLOWED_HOSTS=['www.example.com', 'example.com']
If I switch the commented out line in settings, I get an error saying url may not be in the allowed hosts. I have a number of other definitions in the .env file that work fine although I'm not sure about debug. I've tried all sorts of combinations on the ALLOWED_HOSTS and get the same error. In development I have:
ALLOWED_HOSTS='localhost'
That setting works fine. Any idea what I'm doing wrong?
I found a portion of answer here. Then I did that :
#setting.py
ALLOWED_HOSTS = os.getenv("ALLOWED_HOSTS").split(' ')
#.env
ALLOWED_HOSTS = domain1 domain2 domain3 domain4
And it works.
It looks like you are not loading the .env file properly. Try:
project_folder = os.path.expanduser('~/my-project-dir') # adjust as appropriate
load_dotenv(os.path.join(project_folder, '.env'))
ALLOWED_HOSTS = os.getenv("ALLOWED_HOSTS")
Documentation: https://help.pythonanywhere.com/pages/environment-variables-for-web-apps/

django set multiple allowed hosts

I'm trying to set multiple allowed hosts in django
I have setting configured in production settings production.py as
ALLOWED_HOSTS = env('DJANGO_ALLOWED_HOSTS')
which I can then set on heroku with:
heroku config:set 'DJANGO_ALLOWED_HOSTS' = 'www.example.com'
However how can I add multiple hosts via this method?
You can provide a delimiter then split the string in django
ALLOWED_HOSTS = env('DJANGO_ALLOWED_HOSTS').split(',')
heroku config:set 'DJANGO_ALLOWED_HOSTS' = 'www.example.com,foo.com'
To define multiple values for allowed hosts in settings.py file use like:
ALLOWED_HOSTS = ['000.08.10.11','111.22.33.44','www.abcdefgh.com']

Why is python-pdfkit hanging on printing page with OpenLayers3 content when run with uWSGI and NGINX?

I'm using Django served by uWSGI and NGINX.
Ubuntu 14.04.1 LTS 64-bit
Python 3.4
Django 1.7.4
uWSGI 1.9.17.1-debian (64bit)
NGINX 1.4.6
python-pdfkit 0.5.0
wkhtmltopdf 0.12.2.1
OpenLayers v3.0.0
When I try running pdfkit.from_url(...) to print a map to pdf the request times out.
More specifically it hangs in python's subprocess.py communicate, self._communicate:
with _PopenSelector() as selector:
if self.stdin and input:
selector.register(self.stdin, selectors.EVENT_WRITE)
if self.stdout:
selector.register(self.stdout, selectors.EVENT_READ)
if self.stderr:
selector.register(self.stderr, selectors.EVENT_READ)
while selector.get_map():
...
selector.get_map() always returns a valid result, ensuring an infinite loop.
If I run this in the Django development server (instead of uWSGI+NGINX) everything runs fine.
in my view:
wkhtmltopdfBinLocationString = '/usr/local/bin/wkhtmltopdf'
wkhtmltopdfBinLocationBytes = wkhtmltopdfBinLocationString.encode('utf-8')
#this fixes some leftover python2 assumptions about strings
config = pdfkit.configuration(wkhtmltopdf=wkhtmltopdfBinLocationBytes)
pdfkit.from_url(reportPdfUrl, reportPdfFile, configuration=config, options={
'javascript-delay': 1500
})
Several places I have seen answers along the line of "set the close-on-exec flag on the socket" solving similar issues.
Is this something I can set from my "from_url" options (wkhtmltopdf does not accept it by that name) or can I configure uWSGI to assume 'close-on-exec'? I have not been able to make either of these work, but maybe I just need help with changing my uWSGI customization file:
[uwsgi]
workers = 1
chdir = [...]
plugins = python34
wsgi-file = [...]/wsgi.py
pythonpath = [...]
I tried something like
close-on-exec = true
but that didn't seem to do anything.
NOTE: the wsgi.py file is simple:
"""
WSGI config for dst project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "[my_project].settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
Any thoughts?

Django and Bad Request (400)

I created new django project;
added to my settings.py:
DEBUG = False
ALLOWED_HOSTS= [
'localhost',
'my_site.com'
]
created app test_view;
added hello_world to test_view.views
from django.http.response import HttpResponse
def hello_world(request):
return HttpResponse('Hello World!!!')
added test route to urls.py url(r'test/', 'test_view.views.hello_world');
fixed /etc/hosts
127.0.0.1 localhost my_site.com
Now when i'm trying to access http://my_site.com:8000/test/ django returns Bad Request (400). But when url is http://localhost:8000/test/ I can see my Hello World page. What can be wrong?
UPD:
The same result with DEBUG = True
UPD2:
One more working hostname is ubuntu-virtualbox (computer's name).
But even when I changed computer's name to my_site, ubuntu-virtualbox was still available and my_site returned Bad Request (400)
May it be because of some system settings? (it's clean ubuntu in virtualbox).
Or maybe problem in virtualenv? Is there a way to trace the error?
It might be a bad Cookie. Try deleting them.
It looks like django can see if request isn't passed through dns server. Installation and configuration of bind9 instead of changes in /etc/hosts solved this problem.
You need another line in your hosts file.
127.0.0.1 localhost
127.0.0.1 my_site.com
Then in your ALLOWED_HOSTS...
ALLOWED_HOSTS = [
'localhost',
'.my_site.com', # not 'my_site.com'
]
ALSO, and this is probably important seeing as you are running your site from a virtual machine, when you run the site with python manage.py runserver, run it like this...
python manage.py runserver virtual.server.ip.address:8000
Obviously replace 'virtual.server.ip.address' with that virtual machines actual ip address.
I print *DEBUG = None* and my django works.

Django sessions not working in Internet Explorer

Sessions work perfectly in all other browsers that I have tested.
If I try to get the session id with sessionid = request.COOKIES['sessionid'], I get this error: KeyError: 'sessionid'
This is what I have in my settings.py:
CACHE_BACKEND = 'memcached://127.0.0.1:11211/'
SESSION_COOKIE_DOMAIN = '.vb.is'
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
Sites are vb.is, fiskifrettir.vb.is and hestabladid.vb.is
Server setup is: apache2 (mod_wsgi) and nginx
Setting a cookie on XX.XX won't work in general. See Q#6 here: http://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx and see http://blogs.msdn.com/b/ieinternals/archive/2009/09/19/private-domain-names-and-public-suffixes-in-internet-explorer.aspx.
You can avoid the problem by setting the cookie with domain=WWW.vb.is instead.