Skip to Content
Author's profile photo Hariprasauth R

Getting started with Python development – Bring Your Own Language

In the world of Cloud Foundry, buildpacks provide necessary runtime and framework support for your application to run. The artifacts mentioned in the manifest file are used to determine the buildpack and the command necessary to run the application. SAP Cloud Platform supports the concept of BYOL (Bring Your Own Language) where the users can System buildpacks or the community buildpacks that are possible to be run on Cloud Foundry environment.

In this blog, we will have a look at one such development where we will use the Cloud foundry system buildpack. We will develop and deploy a simple Python application using the python buildpack to the SAP Cloud Platform Cloud Foundry environment.

In this blog, you will learn the following:

  • Deploying a simple Python application on SAP Cloud Platform
  • Consuming the buildpack that is not available in SAP Cloud Platform (BYOL)
  • Project structure/files required to deploy the python application

About the project

In this tutorial, we will use the following framework and server module to develop a web application that displays a simple message.

Flask

This application uses flask which is a web development framework for Python.  This framework also helps to define the port in which you want the application to run. In the main application file, we will use the following lines of code to use the flask library and define the port.

from flask import Flask
import os
app = Flask(__name__)
port = int(os.getenv("PORT", 9009))
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=port)

Gunicorn

Now that we have defined the framework for web development, we need a Web Server Gateway Interface (WSGI) that acts as an interface between the framework and the web server. Gunicorn is a Python WSGI HTTP Server.

Both the dependencies – Gunicorn and Flask must be provided in the requirements.txt file. The project structure looks like this:

–helloworld.py

–manifest.yml

–requirements.txt

  • The helloworld.py is the actual Python script file or the application that contains the application logic. This is where the Flask related details are coded. A sample code is as depicted below:
"""
This is my first python application that is being deployed on SAP Cloud Platform in the Cloud Foundry environment
"""
from flask import Flask
import os

app = Flask(__name__)

port = int(os.getenv("PORT", 9009))

@app.route('/')
def hello_world():
	return 'Hello World! Welcome to SAP Cloud Platform'

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=port)
  • As with any Cloud Foundry application, we can deploy the application with the manifest.yml file that contains the information about the application artifacts. Below is a sample of what can be coded for Python deployment.
---
applications:
- name: myfirstapp
  memory: 128M
  command: python helloworld.py
  buildpack: https://github.com/cloudfoundry/buildpack-python.git

Note the buildpack reference provided in the manifest file. SAP Cloud Platform takes this buildpack for the runtime container of this application.

  • The requirement file contains the information about the dependent libraries.

Flask (or)

Gunicorn

The requirement file would just simply contain the library name. Example: If Flask is required, the file would have the word “Flask”.

Deploying the application

The application can now be deployed from the Cloud Foundry Command Line Interface using the cf push command. It uses the manifest.yml file for the deployment.

 

For the sake of understanding the process of deployment, go through the prompts in the window.

  • The tool reads the manifest.yml to understand the application artifacts like application name, buildpack, etc.
  • The route URL to access the application in SAP Cloud Platform is created
  • The application is bound to the route
  • The application source code is then uploaded
  • The application is started and then the health is monitored
  • The application details like the memory consumption, number of instances, URL, etc. are summarized.

The details of the application can be viewed in the SAP Cloud Platform cockpit.

Upon launching the application URL, the Hello World message is displayed successfully.

Assigned Tags

      20 Comments
      You must be Logged on to comment or reply to a post.
      Author's profile photo Former Member
      Former Member

      Thank you for a helpfull article. Python is a great language to be involved in the world of programming. And the BYOL concept of SAP Cloud Platform and the possibility to build an application which will be run on Cloud Foundry environment. As I've read from Iflexion BLog Python is a good solution to build analytical applications. And if to speak about its flexibility and wide usage I'll probably try to build my own application using your advice and comments.

      Thanks

      Author's profile photo Hariprasauth R
      Hariprasauth R
      Blog Post Author

      Thank you for the feedback, Vadim.

      Author's profile photo Former Member
      Former Member

      Thanks a lot for the wonderful tutorial! Keep it coming!

      Author's profile photo Petar Dochev
      Petar Dochev

      Thanks for the tutorial.

       

      Few comments.

      The screenshots are small and hard to read. I have to zoom to read them.

      The exact content of requirements.txt is not clear.

      It is not clear where Gunicorn is used. I see only Flask referenced in the code.

      Author's profile photo Hariprasauth R
      Hariprasauth R
      Blog Post Author

      Hi Petar,

      Thanks for the comments. I have updated the blog. The requirements.txt would simply contain the word "Flask". And we can either use Flask or if there is a bigger requirement, we could use Gunicorn.

      Author's profile photo Andrew Lunde
      Andrew Lunde

      While this post refers specifically to Cloud Foundry environments, there is now an experimental HANA XS-Advanced python buildpack available for on-premise situations.

      https://blogs.sap.com/2017/08/03/xsa-python-buildpack-and-mta-example/

       

      Please try it out and lend your feedback.

      Author's profile photo Former Member
      Former Member

      Can Python be an full-fledged alternative to Java for SAP Cloud Platform development?

      Author's profile photo Hariprasauth R
      Hariprasauth R
      Blog Post Author

      It depends on the technical requirement per application. This, however, is not limited by SAP Cloud Platform.

      Author's profile photo A K
      A K

      Dont know why I'm getting this error while executing the same code what you have shown here.

       

      -----> Running go build finalize
      No start command specified by buildpack or via Procfile.
      App will not start unless a command is provided at runtime.
      Exit status 0
      Uploading build artifacts cache...
      Uploading droplet, build artifacts cache...
      Uploading droplet...
      Uploaded build artifacts cache (1.1M)
      Uploaded droplet (40.1M)
      Uploading complete
      Stopping instance 0dc7efea-c131-4001-9176-2101b83b6cf6
      Destroying container
      Successfully destroyed container

      0 of 1 instances running, 1 crashed
      FAILED
      Error restarting application: Start unsuccessful

      TIP: use 'cf logs hello-unique --recent' for more information

      Author's profile photo Hariprasauth R
      Hariprasauth R
      Blog Post Author

      Hi A K, Sorry for the late response. Are you sure you are executing the push from the root directory?

      Author's profile photo A K
      A K

      Hari, Thank you for ur response.... It is working fine now

       

      Regards,

      Karthik A

      Author's profile photo Sabarna Chatterjee
      Sabarna Chatterjee

      Hi Hari,

       

      I am facing the below error:

       

      Error staging application: Staging error: Start command not specified.
      
      FAILED

       

      Can you please help me out in this scenario.

       

      Author's profile photo Hariprasauth R
      Hariprasauth R
      Blog Post Author

      Hi,

       

      Are you missing something in the manifest yml file?

      Author's profile photo Sabarna Chatterjee
      Sabarna Chatterjee

      I am able to push the code now. I have used my ‘.py’ code directly from CF CLI .

      Author's profile photo Vignesh Jeyabalan
      Vignesh Jeyabalan

      Hi Hariprasauth R

      I need your help in fixing the issues to establish a connection with HDI container from Python application.

       

      I am using hdbcli package of python which is delivered by SAP .

       

      I downloaded XS PYTHON 1.zip file from SAP Market Place and did a pip locally

       

      When I am trying to deploy the application in cloud foundry it is again trying to do a PIP while deployment as well. I get the below error.

       

      Collecting hdbcli (from -r /tmp/contents263672840/deps/0/requirements.txt (line 3))
      2018-10-09T07:16:09.426+0000 [STG/0] ERR Could not find a version that satisfies the requirement hdbcli (from -r /tmp/contents263672840/deps/0/requirements.txt (line 3)) (from versions: )
      2018-10-09T07:16:09.428+0000 [STG/0] ERR No matching distribution found for hdbcli (from -r /tmp/contents263672840/deps/0/requirements.txt (line 3))
      2018-10-09T07:16:09.450+0000 [STG/0] OUT pip install has failed. You have a vendor directory, it must contain all of your dependencies.
      2018-10-09T07:16:09.450+0000 [STG/0] OUT [31;1m**ERROR**[0m Could not install pip packages: Couldn’t run pip: exit status 1

       

      I have attached my code for your Reference.

      Server.py

      import os
      from flask import Flask
      from cfenv import AppEnv
      from hdbcli import dbapi
      
      app = Flask(__name__)		
      env = AppEnv()		
      
      port = int(os.environ.get('PORT', 3000))
      hana = env.get_service(name='hdi-db')	
      
      @app.route('/')
      def hello():
          #connect to DB using credentials from hdi-db service
          conn = dbapi.connect(address=hana.credentials['host'],
                               port= int(hana.credentials['port']),
                               user = hana.credentials['user'],
                               password = hana.credentials['password'],
                               CURRENTSCHEMA=hana.credentials['schema'])
          cursor = conn.cursor()
      
          #execute SQL query
          cursor.execute("select CURRENT_UTCTIMESTAMP from DUMMY", {})      
          ro = cursor.fetchone()        #get the first result
          cursor.close()
          conn.close()        #close DB connection
      
          #return query results
          return "Current time is: " + str(ro["CURRENT_UTCTIMESTAMP"])  
      
      if __name__ == '__main__':
          app.run(port=port)
      	
      

       

      manifest.yml

      ---
      applications:
      - name: pyapp
        host: pyappvig1
        buildpack: https://github.com/cloudfoundry/buildpack-python.git
        path: .
        command: python Server.py
        services:
         - hdi-dbvig

      These are packages there under vendor folder after a PIP command

       

      This is my Project Structure :

       

       

      Thanks

      Vignesh Jeyabalan

      Author's profile photo Hariprasauth R
      Hariprasauth R
      Blog Post Author

      Hi Vignesh,

      Did you check the version of the libraries? the error message states the version mismatch.

      Regards,

      Author's profile photo Vignesh Jeyabalan
      Vignesh Jeyabalan

      Hi Hariprasauth R

       

      Thanks for the quick response.

      The hdbcli version available for download is 2.3.14 . There are no information available publicly to specify the latest version of the python package. I am using 2.3.14 version only.

      Can you please confirm if the steps i am following here are correct ?

       

      Thanks

      Vignesh Jeyabalan

      Author's profile photo Hariprasauth R
      Hariprasauth R
      Blog Post Author

      I would recommend using this library: https://github.com/SAP/PyHDB

      Author's profile photo Gini Hu
      Gini Hu

      Hi Hariprasauth R,

      Is it possible to connect to on-premise ABAP system from cloud foundry? If yes, how to use in Python?

      Thank you !

       

      Best regards,

      Gini

      Author's profile photo Hariprasauth R
      Hariprasauth R
      Blog Post Author

      Hi Gini,

      Yes. Its absolutely possible. You will get the cloud connector and use that in the code as a service.

      Regards,

      Hari