Developing Flask Application in BAS and consuming it into SAP UI5 Application
2023-11-8 02:57:19 Author: blogs.sap.com(查看原文) 阅读量:8 收藏

Introduction:

API or Application Programming Interface is a set of rules which can be used to retrieve data and send information between solutions in order to build application. SAPUI5 plays a vital role to call API and represent the data seamlessly. This Blog will simplify the process of making a Flask application and connecting the data to SAPUI5 in the Business Application Studio by deploying the application to the BTP Cloud Foundry .

To deploy the flask application into the BTP Cloud Foundry, the first configuration is required at the structure of the  application. Once the configuration is done into the Projects folder of the Business Application Studio, the next step is to connect the generated API to SAP Fiori Application. 

Now lets start the journey of making the flask application, after completion of which the data should be fetched into the fiori application.

To provide the setup and generate the artifact environment, buildpack and path are needed into the manifest.yml file like the below image.Lets define all the necessary framework which will be used in the requirements.txt file.

Once the application is ready, the next step is to provide the exact python version in the runtime.txt file that will be used, as this application is going to be deployed into the BTP Cloud Foundry.

Now to start the application through a specific command in the web server a Procfile is needed like the below image.

As the configuration is done,lets build the flask application using two routes as shown below.In this case the server.py file contains some basic local data that will be displayed through SAPUI5 screen. 

import os
import json
from flask import Flask
application = Flask(__name__)
port = int(os.environ.get('PORT', 8080))
@application.route('/')
def newtest():
    return 'Hello World!'
@application.route('/test',methods=['GET'])
def myfunction():
    data = [
        {'Name': 'Deba', 'Id': 1,'Role':'Developer','Location':'Kolkata'},
        {'Name': 'Kunal', 'Id': 2,'Role':'Support','Location':'Bengalore' },
        {'Name': 'Shila', 'Id': 3,'Role':'Developer','Location':'Hyderabad'},
        {'Name': 'Asish', 'Id': 4,'Role':'Tester','Location':'Bhubaneswar'},
        {'Name': 'Umesh','Id': 5,'Role':'Architect','Location':'Pune'},
        {'Name': 'Raja', 'Id': 6,'Role':'Support','Location':'Hyderabad'}
    ]
    return data
if __name__ == '__main__':
    application.debug = True
    application.run(host='0.0.0.0', port=port)

Now it is ready for deployment. For deploying the application to the Cloud Foundry once the login is done ,”cf push” command is needed. 

After successfully deploying the application into the SAP BTP Cloud foundry, the endpoint will be displayed in the route section in the terminal status or in the space of the BTP Cockpit. The response of the API can also be verified through the Postman after adding ‘/test’ at the end of the url. 

It’s the correct time to fetch the response in SAPUI5 webpage. To kick-start the API fetching process, the initial step is to declare the destination inside of your trial account. 

Below are the details of the destination that is needed to declare into the connectivity section in the SAP BTP Cockpit.

Once the destination setup is done,now the next configuration is needed into the Fiori project structure in Business Application Studio.After creating a fiori application the destination that is defined into the connectivity section is important to mention into the xs-app.json file with source and target like below image.

As soon as the destination details has defined ,the next step is to build the logic to call the API using java-script file in the controller folder. 

onBeforeRendering: function(){
              this.callapi();   

            },
            callapi:function(){
                var that=this; 
                var settings = {
                    "url": this._getModulePath() +"/pythonapi"+"/test",
                    "method": "GET",
                    "timeout": 0,
                  };            
                $.ajax(settings).done(function (response) {
                console.log(response);
                that.getView().getModel("localData").setProperty("/api",response);
                });
            },
            _getModulePath:function(){ 
            var appId=this.getOwnerComponent().getManifestEntry("/sap.app/id");
            var appPath=appId.replaceAll("." , "/");
            var appModulePath=jQuery.sap.getModulePath(appPath);
            return appModulePath;
            }

In the above code after calling the API and showing the response to console, the data is storing into a local-model named as “localData” for showing the data into the view page. 

As defined the logic into the controller ,the local-model is needed which is still not existing into our application.To create the local-model, the details should be defined into the manifest.json file in the models section like the below image.According to the specified details, there is a need to create a file in the model folder with the name “Data.json”. 

Once the logic binding and model defining is done,the upcoming step is to show the data into SAPUI5 webpage. 

<mvc:View controllerName="com.wipro.demfisample.controller.home1"
    xmlns:mvc="sap.ui.core.mvc" displayBlock="true"
    xmlns="sap.m" 
xmlns:core="sap.ui.core" 
>
    <Page id="page" showHeader="false">
        <content>
        <Panel width="30%" class="panel">
        <Label text="Fetched Data From API" design="Bold"/>
      <List  items="{path: 'localData>/api'}"  >
                <CustomListItem >
                    <HBox alignItems="Center" justifyContent="SpaceBetween" >
                        <VBox class="sapUiSmallMarginBegin sapUiSmallMarginTopBottom" >
                             <Text text="Name:{localData>Name}"/>
                             <Text text="Id:{localData>Id}"/>
                             <Text text="Role:{localData>Role}"/>
                             <Text text="Location:{localData>Location}"/>
                            
                        </VBox>
                    </HBox>
                </CustomListItem>
            </List>
           </Panel>
        </content>
    </Page>
</mvc:View>

The previous xml code represents the data  to webpage through List Item where the details are coming from the local-model where the data was stored after calling the API. 

Output:

So after building and deploying the Fiori application, the response of the API is visible into the webpage like the below image. 

Conclusion:

I hope this Blog contains the process and configuration needed for developing a flask application and fetching the data to SAP UI5 webpage using Business Application Studio which will help to customize different application.

Thanks and Regards,

Debashis Ganguly


文章来源: https://blogs.sap.com/2023/11/07/developing-flask-application-in-bas-and-consuming-it-into-sap-ui5-application/
如有侵权请联系:admin#unsafe.sh