How To Use Python Decouple in Django on Ubuntu 16.04

Python Decouple is a great library that helps you strictly separate the settings parameters from your source code.

Web applications relies on several number of parameters to run properly on different environments. To name a few from a Django app settings: database url, password, secret key, debug status, email host, allowed hosts. Most of these parameters are environment-specific. On a development environment you might want to run your application with debug mode on. Also, it’s a clever idea to keep your secret key in a safe place (not in your git repository).

Python Decouple is a great library that helps you strictly separate the settings parameters from your source code. The idea is simple: Parameters related to the project, goes straight to the source code. Parameters related to an instance of the project, goes to an environment file.

In this tutorial we will go over how to install Python Decouple and how to use it in a basic Django application utilizing Alibaba Cloud object storage solution, Spaces.

You May Also Interested in:

 

Python Decouple is compatible and works well with Alibaba Cloud Elastic Compute Service (ECS) servers. As a developer, I prefer the services of Alibaba Cloud to Install Python Decouple on Ubuntu 16.04. Alibaba Elastic Compute (ECS) is highly flexible and you can upgrade the hardware resources anytime when you get more traffic.

Let us now proceed to how you can get it working on your Ubuntu 16.04 LTS system by following these steps below:

Prerequisites

  1. You must have Alibaba Cloud Elastic Compute Service(ECS) activated. If you are a new user, you can get Free Creditsin your Alibaba Cloud account. If you don’t know about how to setup your ECS instance, you can refer to this tutorial or check quick-start guide.
  2. You should setup your server’s hostname.
  3. Access to VNC console in your Alibaba Cloud or SSH client installed in your PC.

Logging to your Console

After completing the prerequisites, login as root user with your root username & password via SSH client (e.g. Putty – You can get Putty from https://www.putty.org ) or VNC console available in your Alibaba Cloud account dashboard.

To complete this tutorial, you will need:

  • One Ubuntu 16.04 server, including a sudo non-root user and a firewall.
  • Alibaba Cloud AccessKey

Python Decouple in Django

Step 1: Update and install dependencies

To install Python we must first update the local APT repository. In your terminal window, we’ll input the command that follows.

  sudo apt-get update

Note that the -y flag answers “yes” to prompts during the upgrade process. Remove the flag if you’d like the upgrade to stop for each prompt.

  sudo apt-get –y upgrade

It is recommended by the Django Software Foundation to use Python 3, so once everything is updated, we can install Python 3 by using the following command:

  sudo apt-get install python3

To verify the successful installation of Python 3, run a version check with the python3 command:

  python3 -V

The resulting output will look similar to this:

 
Output
python 3.5.2

Now that we have Python 3 installed, we will also need pip in order to install packages from PyPi, Python’s package repository.
Let’s install pip the package manager for Python.

sudo apt-get install –y python3-pip

You should see output similar to this:

Output  
pip 8.1.1 from /usr/lib/python3/dist-packages (python 3.5)

Now that we have pip installed, we have the ability to quickly install other necessary packages for a Python environment.

Finally, we will need to install the virtualenv module so that we can set up our programming environment:

sudo pip3 install virtualenv

We are now ready to move into our Python programming environment.

Once it is installed, run a version check to verify that the installation has completed successfully:

virtualenv –version

We should see the following output, or something similar:

Output 
15.1.0

You have successfully installed virtualenv.

Step 2 – Install Django

There are three ways to install Django. We will be using the pip method of installation for this tutorial, but let’s address all of the available options for your reference.

Option 1: Install Django within a virtualenv.

This is ideal for when you need your version of Django to be isolated from the global environment of your server.

Option 2: Install Django from Source.

If you want the latest software or want something newer than what your Ubuntu APT repository offers, you can install directly from source. Note that opting for this installation method requires constant attention and maintenance if you want your version of the software to be up to date.

Option 3: Install Django Globally with pip.

The option we are going with is pip 3 as we will be installing Django globally.

We’ll be installing Django using pip within a virtual environment.

While in the server’s home directory, we have to create the directory that will contain our Django application. Run the following command to create a directory called django-apps, or another name of your choice. Then navigate to the directory.

mkdir Django-apps cd Django-apps

While inside the django-apps directory, create your virtual environment. Let’s call it env.

virtualenv env

Now, activate the virtual environment with the following command:

. env/bin/activate

You’ll know it’s activated once the prefix is changed to (env), which will look similar to the following depending on what directory you are in:

(env) gqadir@ubuntu:$

Within the environment, install the Django package using pip. Installing Django allows us to create and run Django applications.

(env) gqadir@ubuntu:$ pip install django

Once installed, verify your Django installation by running a version check:

(env) gqadir@ubuntu:$ Django-admin –version

This, or something similar, will be the resulting output:
Output 
2.0.1

With Django installed on your server, we can move on to creating a test project to make sure everything is working correctly.

Finally, let’s install Python Decouple**.

pip install python-decouple

You have setup your dependencies within the environment of your Django app and are now ready to set up static and template directories.

 

Step 3 – Add Directories and Assets

With our environment set up with all dependencies, you can now switch to the mysite/mysite directory,

(env) gqadir@ubuntu:$ cd ~/django-apps/mysite/mysite

Within the mysite/mysite directory, run the following commands to create the static and template directories.

(env) gqadir@ubuntu:$ mkdir static && mkdir templates

We’ll next create the subdirectories for images and CSS to live within the static directory.

(env) gqadir@ubuntu:$ mkdir static/img && mkdir static/css

 

Step 4 – Edit CSS and HTML Files

We’ll start by editing the style sheet. You should move into the css directory so that we can add a basic style sheet for our web app.

(env) gqadir@ubuntu:$ cd ~/django-apps/mysite/mysite/static/css

Use nano, or another text editor of your choice, to edit the document.

(env) gqadir@ubuntu:$ nano app.css

Once the file opens, add the following CSS:

app.css
 body {
   margin: 0;
   background-color: #f1f1f1;
   font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
 }

 .container {
   width: 80%;
   border: 1px solid #ddd;
   background-color: #fff;
   padding: 20px;
   margin: 40px auto;
 }

 form {
   margin-bottom: 20px;
   padding: 10px;
   border: 1px solid #ff9900;
   width: 350px;
 }

 table {
   border-collapse: collapse;
   width: 100%;
 }

 table td,
 table th {
   border: 1px solid #eceeef;
   padding: 5px 8px;
   text-align: left;
 }

 table thead {
   border-bottom: 2px solid #eceeef;
 }


Once you are finished, you can save and close the file.

From here, navigate to the templates directory.

(env) gqadir@ubuntu:$ cd ~/django-apps/mysite/mysite/templates

We need to open a file called home.html and add HTML into it for how our basic web app will be displayed. Using nano, open the file so it’s ready for editing:

(env) gqadir@ubuntu:$ nano home.html

Within the document, add the following:

 

home.html 
{% load static %} 
<!DOCTYPE html> 
<html> 
<head>
   <meta charset="utf-8">
   <title>Python Decouple + Django Tutorial</title>
   <link rel="stylesheet" type="text/css" href="{% static 'css/app.css' %}">
 </head>
 <body>
   <center>
   <header>
     <h1>Python Decouple + Django Tutorial</h1>
   </header>
   <main>
     <h2>Congratulations, you’re using Alibaba Cloud!</h2>
   </main>
   </center>
 </body>
 </html>



Save and close the file. The last file we will update is the urls.py file so that it points to your newly created home.html file. We need to move into the following directory:

(env) gqadir@ubuntu:$ cd ~/django-apps/mysite/mysite

Use nano to edit the urls.py file.

(env) gqadir@ubuntu:$ nano urls.py

You can delete everything in the file and then add the following:

urls.py

 from django.conf.urls import url
 from django.views.generic import TemplateView


 urlpatterns = [
    url(r'^$', TemplateView.as_view(template_name='home.html'), name='home'),
]

With these files set up, we can next work on configuring Python Decouple settings.

Step 5 — Use Python Decouple Credentials

Within your virtual environment, navigate to the location of the settings.py file. This is where we will create the settings.ini file to store your credentials separately.

(env) gqadir@ubuntu:$ cd ~/django-apps/mysite/mysite

Create the settings.ini file using touch, a Linux command that creates new, empty files in the directory from which it is called.

(env) gqadir@ubuntu:$ touchsettings.ini

The settings file being created will have an .ini file extension. This file will be looked at by Python Decouple for settings data, and it is also where your settings file will refer to for the API key. You can also use .env as an alternative extension to .ini.

Now, open the settings.ini file using your favorite text editor, such as nano.

(env) gqadir@ubuntu:$ nano settings.ini

In this document, we’ll have a section header, [settings], required by Python Decouple, and will add our credentials by assigning them to variables. Your full file should look like the following:

settings.ini

[settings]
ACCESS_KEY=your-access-key
SECRET_ACCESS_KEY=your-secret-access-key

In order to access these credentials, we’ll need to refer to the settings.ini file from the settings.py file.

In the next step, we’ll go through configuring the settings.py file completely.

Step 6 – Update Settings

Now it’s time to update your settings file with your Spaces credentials so that we can take advantage of the page we’ve setup to display the image.

Ensure that you’re in the correct location to access your settings file.

(env) gqadir@ubuntu:$ cd ~/django-apps/mysite/mysite

Open the file for editing with nano or another text editor:

(env) gqadir@ubuntu:$ nano settings.py

At the top of the file, we’ll need to add an import statement in order to use the config module from Decouple.

settings.py
 ...
 import os
 from decouple import config
 ...

Move down in the file to the allowed hosts and add your server IP.

settings.py

 ...
 ALLOWED_HOSTS = ['your-server-ip']
 ...

Then add storages to the installed apps section of the settings file and remove django.contrib.admin since we won’t be using that in this tutorial. It should look like the following.

settings.py
 ...
 # Application definition

 INSTALLED_APPS = [
     'django.contrib.auth',
     'django.contrib.contenttypes',
     'django.contrib.sessions',
     'django.contrib.messages',
     'django.contrib.staticfiles',
     'storages'
 ]
 ...

Replace and add the highlighted text to the TEMPLATES section of the settings file, so that the project knows where to locate your home.html file.

 settings.py
 ...
 TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'mysite/templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
 ]
 ...

Finally, let’s update your settings at the bottom of the file. We’ll be adding the following below the # Static files section. The first two lines add the reference to the settings.ini file, so that it can retrieve the configuration parameters.

For a terminal location, add the directory into which you would like to import your files. You can add a directory through your Spaces interface in-browser.

settings.py
...
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

ACCESS_KEY_ID = config('ACCESS_KEY')
SECRET_ACCESS_KEY = config('SECRET_ACCESS_KEY')

Now we’ve abstracted our credentials away from the Python code and our settings file is ready to integrate our Django app.

Let’s run the Django web application to verify that everything has been setup correctly.

Step 7 – Run the Application

If you have a UFW firewall set up, let’s first allow inbound traffic to pass through port 8000 by issuing the following command:

(env) gqadir@ubuntu:$ sudo ufw allow 8000

With your virtual environment still activated, let’s navigate to the location of the manage.py file and run the application, using the following commands:

(env) gqadir@ubuntu:$ cd ~/django-apps/mysite 
(env) gqadir@ubuntu:$ python manage.py runserver <your-server-ip>:8000

In a web browser, navigate to the http://your-server-ip:8000 to see the result of the Django application you’ve created.

When you are done with testing your app, you can press CTRL + C to stop the runserver command. This will return you to your programming environment.

When you are ready to leave your Python environment, you can run the deactivate command:

(env) gqadir@ubuntu:$ deactivate

Deactivating your programming environment will put you back to the terminal command prompt.

That’s All. You have now learned how to use Python Decouple in Django on Ubuntu 16.04.

 

Conclusion

In this tutorial you have successfully created a Django application that serves files from Alibaba Cloud while abstracting away the credentials from the Python code. In the process you’ve learned about static files, how to manage static files, how to serve them from a cloud service and how to decouple your configuration parameters from your python settings file.

Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More