Blog Details



Blog Title: Use Oracle Database With Django In Windows
Blogger: hadoleamit@gmail.com
Image: View
Content:

 

In order to connect to Oracle from Python, we need to install cx_Oracle package, which is DB-API 2.0 implementation, using PIP.

Getting Oracle Database ready

We work with Oracle Database 11g Express Edition (XE). If you have not yet installed it, go to Oracle Database 11g Express Edition and download the version relevant to your platform.

  • Download and install Python 3.6 for our platform
  • The python package that is used to connect to Oracle from Python is cx_Oracle
  • Go to directory where pip.exe (or pip3.6.exe) is present and give the following command. Pip.exe is present in /Scripts folder in Windows installation. Check your platform for details.

pip install cx_Oracle

 

Installing Instant Client

In order to access Oracle from Python, you need to install Instant Client that is specific to your platform. Go to Instant Client and select download for your platform. You need to download Instant Client 64 bit if your Python is 64 bit otherwise download 32 bit version. Python edition and Instant Client edition must be same. It is enough to download Instant Client Basic Light version as we need support for only English.

You can check which version of Python you are using

C:\python>python

Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information.

 

Make sure Oracle's BIN directory or InstantClient folder is in system PATH.The following command shows how to add Oracle's BIN directory to system PATH:

c:\>set PATH=%PATH%;C:\oraclexe\app\oracle\product\11.2.0\server\bin

 

If you are using InstantClient, use folder into which you installed InstantClient (for ex: c:\python\instantclient) as follows:

c:\>set PATH=%PATH%;C:\python\instantclient

 

The following program will connect to Oracle Database using username 'gktcs' and password '12345'. In case you are trying to use a different account or a different version of Oracle database then feel free to change the details and experiment..

import os

import cx_Oracle

 

# Connect to hr account in Oracle Database 11g Express Edition(XE)

con = cx_Oracle.connect(“gktcs", “12345", "localhost/xe")

print("Connected!")

con.close()

 

Creating Django Project and Application

We need to install Django Framework using PIP as follows:

pip install django

Installing Django, installs django-admin.exe in Scripts folder of Python installation directory.

 

Let's create a new Django Project called oracledemo and Application called blog in that project with the following commands:

django-admin startproject oracledemo

It will create a new folder oracledemo and places manage.py and another folder oracledemo inside that. Get into oracledemo folder and then run manage.py to create a new application called blog inside that project.

python manage.py startapp blog

 

Configure Django settings.py

  • Open settings.py file that is placed in oracledemo folder, which is inside oracledemo (project) folder.
  • Add application hr as one of the installed applications by adding it to INSTALLED_APPS list.

INSTALLED_APPS = [

'django.contrib.admin’,

'django.contrib.auth’,

'django.contrib.contenttypes’,

'django.contrib.sessions’,

'django.contrib.messages’,

'django.contrib.staticfiles’,

‘blog’,

 ]

 

Modify default database configuration so that Oracle is used as default database.

DATABASES = {

'default': {

          'ENGINE': 'django.db.backends.oracle’,

          'NAME': 'XE’,

          'USER': ‘gktcs’,

          'PASSWORD': ‘12345’,

          'HOST': 'localhost’,

           'PORT': '1521'

        }

    }

 

Creating Model

Create a class that represents JOBS table in Oracle database in oracledemo/hr/models.py file.

class Post(models.Model):

title =models.CharField(max_length=120)

content=models.TextField()

updated=models.DateTimeField(auto_now=True, auto_now_add=False)

timestamp=models.DateTimeField(auto_now=False, auto_now_add=True)

class Meta:

  db_table = “posts"

 

Creating view and template

Create the following function view in oracledemo/blog/views.py to display details of posts from Post table.

def blog_posts (request):

      return render(request,’blog_post.html',{‘posts' : Post.objects.all()})

 

Here is oracledemo/blog/templates/blog_post.html to display details of Jobs in HTML table.

blog_post.html 

<!DOCTYPE html>

<html lang="en">

<head> <meta charset="UTF-8">

   <title>Blogs</title>

 </head>

<body>

<h1>Blog</h1>

    <table width="100%" border="1">

 <tr style="background-color:lightgray">

 <th>Title</th>

 <th>Content</th>

 <th>Updated Time</th>

 </tr>

{% for post in posts %}

             <tr>

   <td>{{post.title}}</td>

  <td>{{post.content}}</td>

   <td>{{post.updated}}</td>  

</tr>

 {% endfor %}

    </table>

</body>

</html>

 

Finally add a new URL in oracledemo/oracledemo/urls.py that invokes blog_posts().

from django.urls

import path import blog.views as blog_views

 

urlpatterns = [

  path(‘post’, blog_views. blog_posts )

 ]

 

Start server after adding Oracle's bin directory or InstantClient directory to system PATH.

>set PATH=%PATH%;C:\oraclexe\app\oracle\product\11.2.0\server\bin

>python manage.py runserver

 

Now go to browser and enter the following URL to get list of Jobs.

http://localhost:8000/post