Skip to content

Instantly share code, notes, and snippets.

@mhsiddiqui
Created August 18, 2019 19:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhsiddiqui/dd129b03bd780c8dadb4b09005fb76ca to your computer and use it in GitHub Desktop.
Save mhsiddiqui/dd129b03bd780c8dadb4b09005fb76ca to your computer and use it in GitHub Desktop.
Deploy Django using Nginx and Gunicorn/uWSGI - Automation with Fabric
from fabric.api import *
PACKAGE_LIST = ['git', 'supervisor', 'postgresql', 'python-pip', 'nginx'] #add all required packages in this list
DB_USER = "db_user" #define your user here
DB_PASS = "db_pass" #define your password here
DB_NAME = "db_name" #define your database name here
def install_package():
sudo('apt-get update')
sudo('apt-get install %s' % (' '.join(PACKAGE_LIST)))
def setup_database():
sudo('psql -c "CREATE USER %s WITH NOCREATEDB NOCREATEUSER " \
"ENCRYPTED PASSWORD E\'%s\'"' % (DB_USER, DB_PASS), user='postgres')
sudo('psql -c "CREATE DATABASE %s WITH OWNER %s"' % (
DB_NAME, DB_USER), user='postgres')
def update_code():
branch = local("git symbolic-ref --short -q HEAD", capture=True)
local('git pull origin %s' % branch)
def install_requirements():
local('pip install -r requirements.txt')
def migrate():
local('python manage.py migrate')
def collectstatic():
local('python manage.py collectstatic')
def configure_supervisor():
"""
Configure supervisor
"""
local('supervisord -c supervisor.conf')
def configure_nginx():
"""
Configure Nginx
:return:
"""
sudo('ln -s nginx.conf /etc/nginx/sites-enabled/myproject.conf')
def restart_supervisor():
sudo('supervisorctl restart myproject_server')
sudo('supervisorctl restart celery_worker')
sudo('supervisorctl restart celery_beat')
def restart_nginx():
sudo('systemctl restart nginx')
@task
def setup():
install_package()
setup_database()
install_requirements()
migrate()
collectstatic()
configure_supervisor()
configure_nginx()
restart_supervisor()
restart_nginx()
@task
def deploy():
update_code()
install_requirements()
migrate()
collectstatic()
restart_supervisor()
@ajharry69
Copy link

This is the most helpful gist I have seen today especially after trying to look for clearer explanations on how to deploy a Django app. Thanks a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment