Creating a Python Application with Django


Options



Before You Begin

Purpose

This tutorial shows you how to create a Python application using the Django framework and how to deploy the application to Oracle Application Container Cloud Service.

Time to Complete

30 minutes

Background

Oracle Application Container Cloud Service lets you deploy Java SE, Node.js, PHP, and Python applications to the Oracle Cloud.

What Do You Need?

  • Access to an instance of Oracle Application Container Cloud Service
  • Python 3.6+
  • The package management system pip
  • cURL 7.0+ with SSL support

Creating the Application Project

  1. Create the django-basic project directory in your local system.

  2. In the django-basic directory, create the requeriments.txt file and add the following content:

    django==1.11
    djangorestframework==3.6.2 
  3. Open a command-line or terminal in Linux and install the project dependencies:

    pip install -r requirements.txt -t modules 
  4. In the command-line, set up a new Django project:

    django-admin startproject tutorial . 
  5. Go to the tutorial directory and create an application:

    python manage.py startapp employees 
  6. Add the employee application and the rest_framework application to INSTALLED_APPS. Edit the tutorial/settings.py file:

    INSTALLED_APPS = (
        ...
        'rest_framework',
        'snippets.apps.SnippetsConfig',
    )

Building the Application

  1. Create the Employee model. Go to employees/models.py and add the following content:

    from django.db import models
    
    class Employee(models.Model):
        firstName = models.TextField()
        lastName = models.TextField()
        email = models.TextField()
        phone = models.TextField()
        title = models.TextField()
        department = models.TextField()
        birthdate = models.TextField() 
  2. In the employees directory, create a file named serializer.py and add the following content:

    from rest_framework import serializers
    from employees.models import Employee
    
    
    class EmployeeSerializer(serializers.ModelSerializer):
        class Meta:
            model = Employee
            fields = ('id', 'firstName', 'lastName', 'email', 'phone', 'title', 'department', 'birthdate')
  3. Edit the employees/views.py file and add the following:

    from django.shortcuts import render
    from django.http import HttpResponse, JsonResponse
    from django.views.decorators.csrf import csrf_exempt
    from rest_framework.renderers import JSONRenderer
    from rest_framework.parsers import JSONParser
    from employees.models import Employee
    from employees.serializers import EmployeeSerializer
    
    @csrf_exempt
    def employee_list(request):
        """
        List all code Employees, or create a new snippet.
        """
        if request.method == 'GET':
            employees = Employee.objects.all()
            serializer = EmployeeSerializer(employees, many=True)
            return JsonResponse(serializer.data, safe=False)
    
        elif request.method == 'POST':
            data = JSONParser().parse(request)
            serializer = EmployeeSerializer(data=data)
            if serializer.is_valid():
                serializer.save()
                return JsonResponse(serializer.data, status=201)
            return JsonResponse(serializer.errors, status=400)
    		
    @csrf_exempt
    def employee_detail(request, pk):
        """
        Retrieve, update or delete a code employee.
        """
        try:
            employee = Employee.objects.get(pk=pk)
        except employee.DoesNotExist:
            return HttpResponse(status=404)
    
        if request.method == 'GET':
            serializer = Employee(employee)
            return JsonResponse(serializer.data)
    
        elif request.method == 'PUT':
            data = JSONParser().parse(request)
            serializer = EmployeeSerializer(employee, data=data)
            if serializer.is_valid():
                serializer.save()
                return JsonResponse(serializer.data)
            return JsonResponse(serializer.errors, status=400)
    
        elif request.method == 'DELETE':
            employee.delete()
            return HttpResponse(status=204) 
  4. In the employees directory, create the urls.py file and add the following content:

    from django.conf.urls import url
    from employees import views
    
    urlpatterns = [
        url(r'^employees/$', views.employee_list),
        url(r'^employees/(?P<pk>[0-9]+)/$', views.employee_detail),
    ]
  5. Edit the tutorial/urls.py file to include the employee application's URLs.

    from django.conf.urls import url, include
    
    urlpatterns = [
         url(r'^', include('employees.urls')),
    ] 
  6. Open the tutorial/settings.py file in a text editor and edit the ALLOWED_HOSTS parameter to allow all the hosts:

    ALLOWED_HOSTS = ['*'] 
  7. Go back the command-line and migrate the database to create the employees table.

    python manage.py makemigration employees
    python manage.py migrate 

Testing Your Application Locally

  1. Open a command-line window (or terminal in Linux) and go to the django-basic directory.

  2. Launch the application:

    python manage.py runserver 
  3. Open other command-line window (or terminal in Linux) and create an employee.

    curl -X POST -i -H "Content-Type: application/json" -d "{\"firstName\":\"john\",\"lastName\":\"Gray\",\"email\":\"john.gray@example.com\",\"phone\":\"1203123\",\"birthdate\":\"1975-05-14\",\"title\":\"Developer Manager\",\"department\":\"IT\"}" http://127.0.0.1:8000/employees/
    
  4. Get all the employees.

    curl -X GET -i http://127.0.0.1:8000/employees/
  5. Update the employee.

    curl -X DELETE -i http://127.0.0.1:8000/employees/1/
  6. Get the employee by ID.

    curl -X GET -i http://127.0.0.1:8000/1/

Preparing Your Application to Cloud Deployment

  1. In the django-basic directory, create the start.sh file and add the following content:

    #!/bin/sh
    export PYTHONPATH=modules
    python app.py 
  2. Create the manifest.json file and add the following content:

    {
      "runtime": {
        "majorVersion": "3.6.0"
      },
      "command": "sh ./start.sh",
      "isClustered": true,
      "release": {
        "version": "1.0"
      },
      "notes": "Python App using Flask and MySQL"
    }
  3. Create the django-basic-dist.zip file with the content of the django-basic directory.

    zip -r django-basic-dist.zip app.py start.sh manifest.json modules requirements.txt

Deploy Your Application to Oracle Application Container Cloud Service

  1. Open the Oracle Application Container Cloud Service console.

  2. In the Applications list view, click Create Application, and select Python.

  3. In the Application section, enter a name for your application, select Upload Archive, and click Browse.

  4. In the File Upload dialog box, select the django-basic-dist.zip file and click Open.

  5. Keep the default values in the Topology section and click Create.

  6. Wait until the application is completely created and copy the URL, you'll use it in the next section.

    Your application could take a few minutes to complete the process.

    EmployeeService application
    Description of this image

Testing Your Application in the Cloud

  1. Enter the URL of your application:
  2. Open a command-line window (or terminal in Linux) and create an employee.

    curl -X POST -i -H "Content-Type: application/json" -d "{\"firstName\":\"David\",\"lastName\":\"Smith\",\"email\":\"david.smith@example.com\",\"phone\":\"1203123\",\"birthdate\":\"1980-02-02\",\"title\":\"Sales Manager\",\"department\":\"Sales\"}"  {{url}}/
    
  3. Get all the employees.

    curl -X GET -i {{ url }}/ 
  4. Delete the employee.

    curl -X DELETE -i {{ url }}/2/
  5. Get the employee by ID.

    curl -X GET -i {{ url }}/2/

Want to Learn More?