Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django uWSGI NGINX Bad Request 400

after receiving a 400-Error when trying to deploy my blog, which I developed, using the django development-server, I started a new test-project (using startproject and doing nothing else - just a little config here and there) - as minimal as possible to keep it as simple as possible.

When I do "manage.py runserver", it shows me a page, saying that I see this, because I have "DEBUG = True" in my settings.

So far so good. No errors.

But if I use uWSGI and NGINX, I get the "Bad Request (400)"-page, again.

Initially I had some import-errors and I had to add some paths to sys.path. But now I get no errors from python, NGINX or uWSGI and still end up with the 400-Error-page.

I've tried the following:

  • DEBUG = False
  • TEMPLATE_DEBUG = False
  • ALLOWED_HOSTS = ['*']
  • ALLOWED_HOSTS = '*'
  • Commented out the 'django.middleware.clickjacking.XFrameOptionsMiddleware' from MIDDLEWARE_CLASSES
  • Using NGINX with uWSGI instead of Apache with mod_wsgi (I stuck with this setup, because I like it, but that didn't solve my problem)

My setup: uWSGI, NGINX and the client (firefox) run from within my notebook (kubuntu 14.04). Vhost/subdomain (cefk_blawg.localhost), which is in the hosts-file (cefk_blawg.localhost 127.0.0.1) and configured correctly in NGINX (I know, because when I use a pyramid-test-project, it actually works like a charm). There is no firewall in the way. Used virtualenv and pip-installed everything in it (django/uwsgi/pillow/mysql-python).

My uwsgi.ini:

[uwsgi]

# Unix socket (full path)
socket = /tmp/cefk_blawg.sock

# Set socket permissions
chmod-socket = 666

# Master process
master = true

# Maximum number of worker processes
processes = 4

# Set timeout
harakiri = 60
harakiri-verbose = true

# Limit post-size
limit-post = 65536

# When to start buffering for post-vars
post-buffering = 1       ## none of these makes my problem go away
#post-buffering = 8192   ## none of these makes my problem go away
#post-buffering = 32768  ## none of these makes my problem go away

# Daemonize
daemonize = /home/cefk/Dokumente/cefk_blawg/uwsgi.log
pidfile = /home/cefk/Dokumente/cefk_blawg/uwsgi.pid

# Limit queue
listen = 64
max-requests = 1000

# Whatever this does .. it works for pyramid (got it from a tutorial)
reload-on-as = 128
reload-on-rss = 96

no-orphans = true
log-slow = true

# This is the full path to my virtualenv
virtualenv = /home/cefk/Dokumente/cefk_blawg/venv

# Django wsgi file
wsgi-file = /home/cefk/Dokumente/cefk_blawg/cefk_info/cefk_info/wsgi.py

# Settings file (this seems to do nothing)
# And it gets set in the wsgi.py-file
env = DJANGO_SETTINGS_MODULE=cefk_info.settings

# Set domain (this seems to do nothing)
#domain = cefk_blawg.localhost

# Django-project base directory (this seems to do nothing)
#chdir = /home/cefk/Dokumente/cefk_blawg/cefk_info

# This seems to do nothing
#pythonpath=/home/cefk/Dokumente/cefk_blawg/cefk_info/cefk_info/

# Set vhost (this seems to do nothing)
#vhost = true

# Clean up environment on exit
vacuum = true
#

My wsgi.py-file:

import os
import pprint
import site
import sys
from django.core.wsgi import get_wsgi_application

base_parent = '/home/cefk/Dokumente/cefk_blawg/'
base = '/home/cefk/Dokumente/cefk_blawg/cefk_info/'

sys.path.append(base_parent)
sys.path.append(base)

site.addsitedir(
    '/home/cefk/Dokumente/cefk_blawg/venv/local/lib/python2.7/site-packages'
)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cefk_info.settings")

activate_env = '/home/cefk/Dokumente/cefk_blawg/venv/bin/activate_this.py'
execfile(activate_env, dict(__file__=activate_env))

# I stole this shamelessly from another stackoverflow-post - this is good to have
class LoggingMiddleware:
    def __init__(self, application):
        self.__application = application

    def __call__(self, environ, start_response):
        errors = environ['wsgi.errors']
        pprint.pprint(('REQUEST', environ), stream=errors)

        def _start_response(status, headers, *args):
            pprint.pprint(('RESPONSE', status, headers), stream=errors)
            return start_response(status, headers, *args)

        return self.__application(environ, _start_response)

application = LoggingMiddleware(get_wsgi_application())

This is my request/response, which I get from the LoggingMiddleware in wsgi.py:

(
    'REQUEST',
    {
        'CONTENT_LENGTH': '',
        'CONTENT_TYPE': '',
        'DOCUMENT_ROOT': '/home/cefk/Dokumente/cefk_blawg/cefk_info/cefk_info',
        'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'HTTP_ACCEPT_ENCODING': 'gzip, deflate',
        'HTTP_ACCEPT_LANGUAGE': 'de,en-US;q=0.7,en;q=0.3',
        'HTTP_CACHE_CONTROL': 'max-age=0',
        'HTTP_CONNECTION': 'keep-alive',
        'HTTP_DNT': '1',
        'HTTP_HOST': 'cefk_blawg.localhost',
        'HTTP_USER_AGENT': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:29.0) Gecko/20100101 Firefox/29.0',
        'PATH_INFO': '/',
        'QUERY_STRING': '',
        'REMOTE_ADDR': '127.0.0.1',
        'REMOTE_PORT': '42518',
        'REQUEST_METHOD': 'GET',
        'REQUEST_URI': '/',
        'SERVER_NAME': 'cefk_blawg.localhost',
        'SERVER_PORT': '80',
        'SERVER_PROTOCOL': 'HTTP/1.1',
        'UWSGI_SCHEME': 'http',
        'uwsgi.node': 'lt',
        'uwsgi.version': '2.0.5.1',
        'wsgi.errors': <open file 'wsgi_errors', mode 'w' at 0x7ff4337110c0>,
        'wsgi.file_wrapper': <built-in function uwsgi_sendfile>,
        'wsgi.input': <uwsgi._Input object at 0x7ff437271e70>,
        'wsgi.multiprocess': True,
        'wsgi.multithread': False,
        'wsgi.run_once': False,
        'wsgi.url_scheme': 'http',
        'wsgi.version': (1, 0)
    }
)
('RESPONSE', '400 BAD REQUEST', [('Content-Type', 'text/html')])
[pid: 2652|app: 0|req: 1/1] 127.0.0.1 () {42 vars in 675 bytes} [Thu Jun 12 17:16:59 2014] GET / => generated 26 bytes in 150 msecs (HTTP/1.1 400) 1 headers in 53 bytes (1 switches on core 0)

EDIT: This was my nginx-config (notice, that the folder-name might have changed in the meantime - so ignore that, please):

# Server configuration
server {
    # Make site accessible from http://cefk_blawg.localhost/
    server_name cefk_blawg.localhost;

    root /home/cefk/Dokumente/cefk_blawg_django;

    # Set charset
    charset utf-8;
    client_max_body_size 100M;

    location /static {
        autoindex on;
        alias /home/cefk/Dokumente/cefk_blawg_django/static;
    }

    location /media {
        autoindex on;
        alias /home/cefk/Dokumente/cefk_blawg_django/media;
    }

    ################################
    # Port-based (old)             #
    ################################
    #location / {
    #    try_files $uri @application;
    #}  

    #location @application {
    #    include /etc/nginx/uwsgi_params;
    #    uwsgi_pass 127.0.0.1:8000;
    #}
    ################################
    # /Port-based (old)            #
    ################################

    location / {
        include /etc/nginx/uwsgi_params;
        uwsgi_pass unix:///tmp/cefk_blawg.sock;
    }
}

/EDIT

I'm out of ideas.

Please help.

like image 860
doh-nutz Avatar asked Jun 12 '14 19:06

doh-nutz


4 Answers

Since I asked this question over 5 years ago, I might be wrong. But I'm gonna answer it now as best I can, since all the answers coming up seem to be far off from my solution(s).

I recently used Django again for a few projects and had a similar problem.

List of what I was doing wrong:

  • Had uwsgi installed in the virtualenv as well as globally on the system
  • Wrong path to the app in the uwsgi-config
  • Wrong path to the virtualenv in the uwsgi-config
  • Permissions for the socket-file for connecting uwsgi and nginx were set incorrectly

That's all I can think of, what I've been doing wrong, back in the day.

I hope this helps all of you, who struggle with the setup.

like image 139
doh-nutz Avatar answered Nov 15 '22 20:11

doh-nutz


In settings.py

ALLOWED_HOSTS = ['*']

Will solve it

like image 11
Aseem Avatar answered Nov 15 '22 18:11

Aseem


You can set DEBUG = True on your server, restart uwsgi service and check the django's debug output in your browser. The fact you don't see any errors with django's development server doesn't mean the error is related to nginx or uwsgi services.

like image 10
Alex Avatar answered Nov 15 '22 20:11

Alex


Okay so I got this same error but I finally figured it out. (At least for me). I pray to god this works for you because I wasted a day on this.

If you're like me you used: http://uwsgi-docs.readthedocs.org/en/latest/tutorials/Django_and_nginx.html as a tutorial to get the basic setup. I got uwsgi to work over http and it seemed to work over tcp socket. As soon as I tried to hook up nginx, I kept getting 400 errors. It specifically says create a file name my_site.conf and link that to sites-enabled. Well if you check sites-enabled you should see a file named default. Notice this file isn't named default.conf. Try renaming my_site.conf to my_site and make sure to re-link.

TDLR: Unlink my_site.conf. Rename my_site.conf to my_site. Link my_site to sites-enabled

like image 1
Evan Marshall Avatar answered Nov 15 '22 20:11

Evan Marshall