[Solved]-Hosting Django app with Waitress

26πŸ‘

Tested with Django 1.9 and Waitress 0.9.0

You can use waitress with your django application by creating a script (e.g., server.py) in your django project root and importing the application variable from wsgi.py module:

yourdjangoproject project root structure

β”œβ”€β”€ manage.py
β”œβ”€β”€ server.py
β”œβ”€β”€ yourdjangoproject
β”‚Β Β  β”œβ”€β”€ __init__.py
β”‚Β Β  β”œβ”€β”€ settings.py
β”‚Β Β  β”œβ”€β”€ urls.py
β”‚Β Β  β”œβ”€β”€ wsgi.py

wsgi.py (Updated January 2021 w/ static serving)

This is the default django code for wsgi.py:

import os
    
from django.core.wsgi import get_wsgi_application
    
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "yourdjangoproject.settings")
    
application = get_wsgi_application()

If you need static file serving, you can edit wsgi.py use something like whitenoise or dj-static for static assets:

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "yourdjangoproject.settings")

"""
YOU ONLY NEED ONE OF THESE.
Choose middleware to serve static files. 
WhiteNoise seems to be the go-to but I've used dj-static 
successfully in many production applications.
"""

# If using WhiteNoise:
from whitenoise import WhiteNoise
application = WhiteNoise(get_wsgi_application())

# If using dj-static:
from dj_static import Cling
application = Cling(get_wsgi_application())

server.py

from waitress import serve
    
from yourdjangoproject.wsgi import application
    
if __name__ == '__main__':
    serve(application, port='8000')

Usage

Now you can run $ python server.py

πŸ‘€aboutaaron

9πŸ‘

I managed to get it working by using a bash script instead of a python call. I made a script called β€˜startserver.sh’ containing the following (replace yourprojectname with your project name obviously):

#!/bin/bash
waitress-serve --port=80 yourprojectname.wsgi:application

I put it in the top-level Django project directory.

Changed the permissions to execute by owner:

chmod 700 startserver.sh

Then I just execute the script on the server:

sudo ./startserver.sh

And that seemed to work just fine.

πŸ‘€chrislarson

Leave a comment