This article was written as an article for December 15th of SAP Advent Calendar 2020.
This time, I would like to create a WebAPI with Phthon and run it on a CF environment. I was able to create a WebAPI in about 3 days of python history.
Prepare to install the module used in this program.
First, prepare "requirements.txt" for batch installation. Use this file to manage Python packages across different environments You can install it if you want.
requirements.txt
Flask==0.12.2
flask-cors
After saving requirements.txt, use python's package management software Install the required modules.
$ pip install -r requirements.txt
Specifies the Python version to use in the CF environment.
runtime.txt
python-3.6.12
Create a deployment definition file for the CF environment.
For
manifest.yml
applications:
- name: <app name>
path: .
memory: 256M
command: python server.py
I would like to write a WebAPI in Python. The code is shown below.
server.py
import os
import json
import pickle
from flask import Flask, request, abort
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
port = int(os.environ.get('PORT', 3000))
@app.route('/')
def hello():
return "Hello World"
@app.errorhandler(404)
def error_not_found(error):
result = "{\"message\": \"pickle file not found\"}"
return result, 404
if __name__ == '__main__':
app.run(host='0.0.0.0', port=port)
Deploy the created program to the CF environment. Here, I will upload it to the trial environment.
Specify the execution environment and log in.
$ cf api <API endpoint>
The
If the connection is successful, you will be authenticated with your email and password. Log in using the email and password you registered.
Specify the organization to connect to.
The
Now that you have specified the CF environment to deploy to, deploy to the CF environment.
cf push <app name>
Successful deployment adds the application to SAP Cloud Platform Cockpit
The Status is displayed as RUNNING
.
Now let's execute the created API. Click the URL listed in Application Routes.
This time, I made it so that it works when I access'/'. If successful, the following screen will be displayed.
I'm using Python3.6.12 this time, but the version of PHP available in the CF environment seems to vary. When I made a prototype in the past, I was using Python3.5.10. For this post, I tried to deploy the same program to the CF environment, but Python 3.5.10 was no longer available. You may not want to use a very old version of Python.
https://docs.cloudfoundry.org/buildpacks/python/index.html
Recommended Posts