In this blog post we will learn how we can integrate UI5 with Python Django framework and deploy the application in the Red Hat Cloud Platform.

In my previous blog (How to create an Android PhoneGap plugin for UI5 Mobile) we have seen how can we create an Android plugin to save the text file locally from UI5 Mobile, as a next step we will create a simple server application where we can upload the same text file which we stored from android app to read transaction data and update our server database table.

Red Hat Cloud Platform (www.openshift.com) provides both free and enterprise PAAS and support for various technologies like Java, Php, Perl, Python, Ruby, Node.js. For this blog we will use the free services.  The prerequisite for this blog is basic knowledge on Git, UI5 and Python Django framework.

Creating an OpenShift Account:

First let’s create an account in the Red Hat Cloud Platform (www.openshift.com) providing basic details, activate your account by clicking on the email verification. Now Add a new application in your openshift cockpit clicking on Add Application under the Applications tab. Choose the technology under ‘browse by tag’ which you want for this application (which is also called as Cartilages in the world of openshift) we will choose the latest version of python with django – Django 1.6 and Python 3 on OpenShift.

django 1.6.png

Give the name for your application, I am using “DemoAppServer” and If you already have git repo with active code you can connect the same here by providing the valid git repo link in source code field, for now I am continuing with the standard Openshift Python Git repo link(https://github.com/rancavil/django-py3-openshift-quickstart.git) to install django and also if you want the application to be scalable , you can choose the scalable option during this step and click on Create Application.

Openshift creates a new git repo for you Application with the copy of standard git python repo which we have provided in the previous step.

making code changes.png

As a next step to continue with your development you need to clone the git repo which Openshift had created for your application to your local machine. For the same go to settings tab in OpenShift cockpit and update your ssh public key. OpenShift uses a public key to securely encrypt the connection between your local machine and your application and to authorize you to upload code.

Installing Git Bash and Connecting to OpenShift:

In this step we will see how we can create ssh key in your machine to connect with your Openshift account. To create the ssh key first download and install Git Bash from the location (http://git-scm.com/downloads).

While installing Enable the ‘Git Bash Here’ option and

gui bash here.png

‘Use Git from Git Bash only’ then finish the installation. The screenshots for both the above two options are attached.

bit bash only.png

Once the installation is completed, Open your Git Bash and give the following command

ssh-keygen -t rsa -C “your_email@example.com

Which creates a new ssh key, using the provided email as a label, Generating public/private rsa key pair.

Enter file in which to save the key (c:\Users\<your administrator>\.ssh\id_rsa): [Press enter]

Next, you’ll be asked to enter a passphrase, then confirm the same.

ssh create masked.png

Go to the following location ‘C:\Users\<your administrator>\.ssh’ and you can find the file id_dsa.pub , right click that file and open with text editor, copy the contents and paste the same in the settings tab public key field of your Openshift account.

ssh pub masked.png

Now open Git Bash and git the command followed by the repository of your application to clone the same.

Git clone <your git repo link from openshift>

git clone demoserverapp.png

You can find the application code downloaded to the location

‘C:\Users\<your administrator>\<your application name>’

Developing our DemoAppServer:

Let’s open your application folder and see the following folder hierarchy,

openshift folder heir.png

We need to edit the urls.py file to redirect our call to the custom method in the views.py , I give the method name as home in the urls.py for the landing url, I would always prefer using the Python IDLE for editing .py files since the indentation as a significant role in python.

Now open Views.py, add a custom method home, find the code below. The following code will simple call the home.html file which I have mentioned in the template folder and send as a response to the http call.

Urls.py


from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
admin.autodiscover()
urlpatterns = patterns('',
    # Examples:
    url(r'^$', 'openshift.views.home', name='home'),
    url(r'^upload', 'openshift.views.upload_file', name='upload_file'),
    url(r'^create', 'openshift.views.create_table', name='create_table'),
    url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes':True}),
    url(r'^admin/', include(admin.site.urls)),
)





The home.html (UI5 code) is mentioned below.

home.html


<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta http-equiv='Content-Type' content='text/html;charset=UTF-8'/>
        <script src="https://sapui5.netweaver.ondemand.com/sdk/resources/sap-ui-core.js"
                id="sap-ui-bootstrap"
                data-sap-ui-libs="sap.ui.commons,sap.ui.table"
                data-sap-ui-theme="sap_bluecrystal">
        </script>
        <!-- add sap.ui.table,sap.ui.ux3 and/or other libraries to 'data-sap-ui-libs' if required -->
        <script type="text/javascript">
            var layout = new sap.ui.commons.layout.MatrixLayout();
            layout.setLayoutFixed(false);
            // create the uploader and disable the automatic upload
            var oFileUploader = new sap.ui.commons.FileUploader({
                name: "upload",
                multiple: false,
                maximumFileSize: 0.5,
                mimeType: "text",
                fileType: "txt",
                uploadOnChange: false,
                uploadUrl: "http://demoappserver-exaag.rhcloud.com/upload",
                fileSizeExceed: function (oEvent) {
                },
                typeMissmatch: function (oEvent) {
                },
                uploadComplete: function (oEvent) {
                    var sResponse = oEvent.getParameter("response");
                    if (sResponse) {
                        var myarray = [];
                        var sRes = JSON.parse(sResponse);
                        var myJSON = "";
                        for (var i = 0; i < sRes.length; i++) {
                            var item = {
                                "amount": sRes[i],
                            };
                            myarray.push(item);
                        }
                        myJSON = JSON.stringify(myarray);
            
                        var oModel = new sap.ui.model.json.JSONModel();
                        oModel.setData({modelData: JSON.parse(myJSON)});
                        oTable.setModel(oModel);
                        oTable.bindRows("/modelData");
                    }
            }});
            //Define some sample data
            var aData = [
                {amount: "2000"}
            ];
            //Create an instance of the table control
            var oTable = new sap.ui.table.Table({
                title: "Transaction Data",
                visibleRowCount: 10,
                firstVisibleRow: 3,
                width: "500px",
                selectionMode: sap.ui.table.SelectionMode.Single
            });
            //Define the columns and the control templates to be used
            var oColumn = new sap.ui.table.Column({
                label: new sap.ui.commons.Label({text: "Amount credited (INR)"}),
                template: new sap.ui.commons.TextView().bindProperty("text", "amount"),
                width: "200px"
            });
            oTable.addColumn(oColumn);
            //Create a model and bind the table rows to this model
            var oModel = new sap.ui.model.json.JSONModel();
            oModel.setData({modelData: aData});
            oTable.setModel(oModel);
            oTable.bindRows("/modelData");
            layout.createRow(oFileUploader);
            // create a second button to trigger the upload
            var oTriggerButton = new sap.ui.commons.Button({
                text:'Upload',
                press:function() {
                // call the upload method
                oFileUploader.upload();
            }
            });
            layout.createRow(oTriggerButton);
            layout.createRow(oTable);
            layout.placeAt("content");
        </script>
    </head>
    <body class="sapUiBody" role="application">
        <h1> DemoApp Server </h1>
        <div id="content"></div>{% csrf_token %}
    </body>
</html>





Open urls.py to add the custom method for uploading the text file and update the server datable, now open the views.py and paste the below mentioned code.

Views.py


from django.shortcuts import render_to_response
from django.core.context_processors import csrf
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from django import forms
import os
import sqlite3
import json
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
MEDIA_ROOT = os.path.join(os.environ['OPENSHIFT_DATA_DIR'], 'media')
STATIC_ROOT = os.path.join(BASE_DIR, '..', 'static')
class UploadFileForm(forms.Form):
    title = forms.CharField(max_length=50)
    file  = forms.FileField()
def home(request):
    return render_to_response('home/home.html')
@csrf_exempt
def upload_file(request):
    cont = ""
    conn = sqlite3.connect(os.path.join(os.environ['OPENSHIFT_DATA_DIR'], 'sqlite3.db'))
    cursor = conn.cursor()
    count = 0
    for upfile in request.FILES.getlist('upload'):
        for chunk in upfile.chunks():
            cont = str(chunk)[2:][:-1]
    val = []
    val = str(cont).split("n")
    conn = sqlite3.connect(os.path.join(os.environ['OPENSHIFT_DATA_DIR'], 'sqlite3.db'))
    cursor = conn.cursor()
    for el in val:
        if el.find('r') > -1 :
            cmd = "INSERT INTO transactiontb VALUES ('" + str(el)[:-3] + "')"
        else:
            cmd = "INSERT INTO transactiontb VALUES ('" + str(el) + "')"
        cursor.execute(cmd)
    conn.commit()
    cmd = "SELECT * FROM transactiontb"
    cursor = conn.cursor()
    count = 0
    lines = []
    for res in cursor.execute(cmd):
        lines.insert(count,str(res)[2:][:-3])
        count = count + 1
    conn.close()
    return HttpResponse(json.dumps(lines))
def create_table(request):
    conn = sqlite3.connect(os.path.join(os.environ['OPENSHIFT_DATA_DIR'], 'sqlite3.db'))
    cursor = conn.cursor()
    cmd = "CREATE TABLE transactiontb(amt text)"
    cursor.execute(cmd)
    conn.commit()
    conn.close()
    return HttpResponse("success")





This code will read the uploaded transaction data file , read the amount data and update the same in the database table (transactiondata), as a first step I had already created the database table transactiontb using the create_table method. Also for the time being I have used csrf_exempt , and added a small trick in the code to convert the binary data to string using string functions in python.

After updating the server, this method also returns the complete transaction data details back to UI5 in the JSON format and we will display the same in a table.

After making the code changes right click the folder ‘C:\Users\<your administrator>\<your application name>’ and click on the GUI Bash Here and continue with your git updation comments below.

Git add .

Git commit –m “my changes”

Git push


Find the sample text file with just amount over each line,

transactionData.png

Here is the OpenShift DemoAppServer link (http://demoappserver-exaag.rhcloud.com/).

The final output is here

FinalOutput.png

Feel free to comment for any queries, Thank you.

Updating the github link : Rottwei/DemoAppServerUI5 · GitHub

Kishore Kumar

To report this post you need to login first.

3 Comments

You must be Logged on to comment or reply to a post.

  1. Simone Milesi

    Really nice example!

    I’m working with Django and i’ve to integrate many UI5 apps and i’m looking for a way to do it nicely.

    I prefer to work with XML Views instead of pure JS: got anyexperience with them?

    (0) 

Leave a Reply