Monday, 26 July 2021

*Episode 27* PYTHON (Deploying On Heroku in Django)


 Deploying on Heroku


This episode covers :-


 1) How to deploy to Heroku.


  • Setup :-

    Create a folder outside the projects folder:

Terminal

mkdir deployments

cd deployments

mkdir heroku

cd heroku

python3 -m venv venv

source venv/bin/activate

pip install django django-heroku gunicorn

pip freeze > requirements.txt

django-admin startproject mysite .

python manage.py runserver


     django-heroku package installs some dependencies like psycopg2 for PostgreSQL support and whitenoise for serving static files straight from the app.

Terminal

├── deployments # < here

│ ├── heroku # < here

├── projects


  •  Creating a Heroku app :-

     Visit https://samuli.to/Heroku and create an account:



     Press Create new app:





     Rest of the chapter shows sn-01 as the app name. Replace it with the name of your app.


  •  Installing Heroku CLI :-

 Installation in Windows :-


     Visit https://samuli.to/Heroku-CLI and download the Windows installer.


Installation in macOS :-


Terminal

xcode-select --install

brew install heroku/brew/heroku


Installation in Ubuntu :-


Terminal

sudo snap install --classic heroku


Authenticating with a browser :-


     Use heroku login in terminal to login:

Terminal

heroku login

heroku: Press any key to open up the browser to login or q \

to exit:

Logging in... done

Logged in as user@example.org


  •  Creating a Procfile :-

     Create a file called Procfile in the project root and write this line in it:

Procfile contents

web: gunicorn mysite.wsgi


  •  Updating the settings.py file :-

     Edit settings.py file and import django_heroku package on the top and change DEBUG and ALLOWED_HOSTS variables:

mysite/settings.py

import django_heroku # < here

import os

DEBUG = False # < here

ALLOWED_HOSTS = ['sn-01.herokuapp.com'] # < here


     Add the following lines at the bottom of the file:

mysite/settings.py

django_heroku.settings(locals())

try:

from .local_settings import *

except ImportError:

pass


     Create a local_settings.py file:

mysite/local_settings.py

DEBUG = True

ALLOWED_HOSTS = []


  • Creating the repository :-

    Visit https://samuli.to/Git and install Git.


    Create a .gitignore file in the site root:

.gitignore file

venv

local_settings.py

db.sqlite3

*.pyc

__pycache__/

*.py[cod]

.DS_Store


     Visit https://samuli.to/Dj-Gitignore too see more comprehensive .gitignore example.


     Initialise git repository and push it:

Terminal

git init

git add .

git commit -m "Initial"

heroku git:remote -a sn-01

git push heroku master


     Run migrate and create a superuser:

Terminal

heroku run python manage.py migrate

heroku run python manage.py createsuperuser


     Visit your app admin pages in https://sn-01.herokuapp.com/admin/.


     Note: we don’t see the welcome screen on the frontpage because the production site is not in debug mode. You get “The requested URL / was not found on this server.” instead because we don’t have a view for the homepage.


  •  Pushing changes :-

      Let’s add a homepage and some CSS styling. The django-heroku package installs the Whitenoise package that allows your web app to serve its own static files. Check out the next chapter on how to serve static files and user-uploaded
files from Amazon AWS.
Terminal
django-admin startapp blog

    Add an index view:
blog/views.py
from django.shortcuts import render
def index(request): # < here
return render(request, 'blog/index.html')

     Create an index.html file with this content:
blog/templatesblogindex.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Blog</title>
<link rel="stylesheet" href="{% static 'blog/css/site.c\
ss' %}">
</head>
<body>
<div id="content">
<h1>Home</h1>
</div>
</body>
</html>

     You have to create the folder structure: blogtemplatesblog.

     Create a site.css file with this content:
blog/staticblogcss/site.css
h1 { color: red;}

     You have to create the folder structure: blogstaticblogcss/.

     Edit urls.py file and add the index path:
mysite/urls.py
from django.contrib import admin
from django.urls import path
from blog import views # < here
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name='index') # < here
]

     Add ‘blog’ to the INSTALLED_APPS list:
mysite/settings.py
INSTALLED_APPS = [
...
'django.contrib.staticfiles',
'blog', # < here
]

Terminal
git add .
git commit -m "Add Blog app"
git push heroku master

     Visit the production site homepage and you should see this:


     Note: we didn’t have to run “heroku run python manage.py migrate” because we
didn’t make any changes that require database updates.

  • Updating the database :-

    Let’s create a Post model and update the database:
blog/models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=255, default='')

     Register it in admin.py:
blog/admin.py
from django.contrib import admin
from .models import Post
admin.site.register(Post)

     Run local migrations:
Terminal
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
python manage.py runserver

     Login and create a post item to see that it works locally before you push it.

     Push the changes:
Terminal
git add .
git commit -m "Add Post model"
git push heroku master

     Apply changes to the remote database:
Terminal
heroku run python manage.py migrate


Visit your heroku app admin page and add content:

Summary :-

  • django-heroku adds settings configuration. This includes things like DATABASE_URL so that you don’t have to add database configuration manually. It also install some extra packages like whitenoise that allows you to serve static files directly from the app without using Nginx, Amazon S3 or any other similar solution.
  • Use “pip freeze > requirements.txt” to generate a dependency list. These will be installed automatically when you push the code.
  • Remember to set DEBUG = False and configure ALLOWED_HOSTS variable in the settings.py file for production environments.
  • It’s useful to create multiple settings files like local_settings.py to add environment specific configuration.
  • Heroku CLI allows you to interact with the platform using a command line. It requires GIT to work.
  • You can run remote commands with “heroku run <command>”. For example, if you make changes to the database schema, you should run “heroku run python manage.py migrate”.
  • Use “git push heroku master” to push changes to the platform. Check out the “Heroku Pipelines” chapter on how to create a proper deployment flow.

👈Episode 26(P).                                                                           Episode 28(P)👉
Share this Post

PRINT THIS POST

No comments:

Post a Comment

If you have any doubts. Please let me know.

Featured post

*Episode 1* MCQ for Govt. Job/ Private Job/ MNCs

  Topic:- One Word Substitution 1) Especially skilled in storytelling  Answer:- Raconteur 2) Fear of loneliness Answer:- Eremophobia  3) Usa...