利用SAP Tech Bytes:CF应用将CSV文件上传到SAP HANA云的HANA数据库中

299 阅读4分钟

前提条件

  • 在SAP HANA云中创建并运行SAP HANA数据库的SAP BTP试用账户
  • cf 命令行工具(CLI)。

我不会重复其中的步骤,比如如何使用cf CLI 登录到您的 SAP BTP 账户。但我将介绍我们将在此进行的工作/实验的额外内容。

让我们来看看这个应用程序

在讨论应用程序的实施细节之前,让我们先看看它的外观和功能。

一旦启动。

  1. 它检查SAP HANA云数据库中是否存在预期的模式并连接到它
  2. 允许您上传任何CSV或TXT文件(请注意10MB限制)。
  3. 一旦您预览了上传的文件,您就可以将其持久化到您的SAP HANA db实例中。

我们可以看到一个具有相应结构的表被创建,数据被上传。

如果我们上传另一个文件,那么这个表的结构将被重新创建。

实施

在SAP HANA db中为暂存区创建一个服务...

检查hana 服务的可用计划。

cf marketplace -e hana

hana 下面的命令创建了一个名为hdb-staging-schema 的服务实例,计划为schema ,数据库模式名称为STAGING4UPLOADS

cf create-service hana schema hdb-staging-schema -c '{ "schema" : "STAGING4UPLOADS" }'

一旦创建,你应该在SAP BTP Cockpit中看到该服务。

...和一个服务密钥,以便我们访问该模式中的数据。

cf create-service-key hdb-staging-schema hdb-staging-schema-sk
cf service-key hdb-staging-schema hdb-staging-schema-sk

我们可以用它来连接到数据库和模式。

CONNECT STAGING4UPLOADS PASSWORD "Your_Long_Password_From_The_ServiceKey";
SELECT Current_User, Current_Schema FROM dummy;

实现我们的应用程序

loadfile_mvp.py

主文件,包含最小的所需逻辑(因此mvp 在名称中)。

from io import StringIO
import streamlit as st
import hana_ml.dataframe as dataframe
from cfenv import AppEnv
import pandas as pd

st.set_page_config(
   page_title="CSV-to-HDB",
   page_icon="https://hana-cockpit.cfapps.us10.hana.ondemand.com/hcs/sap/hana/cloud/assets/images/sap_logo.svg",
   layout="wide",
)

st.title('CSV-to-HDB')

env = AppEnv()

HANA_SERVICE = 'hdb-staging-schema'
hana = env.get_service(name=HANA_SERVICE)

# Instantiate connection object
conn = dataframe.ConnectionContext(address=hana.credentials['host'],
                             port=int(hana.credentials['port']),
                             user=hana.credentials['user'],
                             password=hana.credentials['password'],
                             encrypt='true',
                             sslTrustStore=hana.credentials['certificate'])

st.write(f'1. Connected to the schema {conn.get_current_schema()}')

df_data = None

some_file = st.file_uploader("2. Upload a file to be loaded into SAP HANA Cloud db", type={"csv", "txt"})
if some_file is not None:
     # To read file as bytes:
     bytes_data = some_file.getvalue()
     #st.write(bytes_data)

     # To convert to a string based IO:
     stringio = StringIO(some_file.getvalue().decode("utf-8"))
     #st.write(stringio)

     # To read file as string:
     string_data = stringio.read().splitlines()
     st.write('File preview (up to 5 lines):', string_data[:5])

# Load CSV into pandas DataFrame

df_data = None
if some_file is not None:
    df_data = pd.read_csv(some_file, sep=None).convert_dtypes()
    
st.write(f"Pandas dataframe size: {0.0 if df_data is None else round(df_data.memory_usage(deep=True).sum()/1024/1024, 2)} MB")
st.write('Dataframe (up to 5 rows):', df_data if df_data is None else df_data.head(5))

# Load data to SAP HANA
service_schema = hana.credentials['schema']
target_table = st.text_input('HANA table name: ', 'STAGING')

if st.button('3. Persist data into the HANA db') and df_data is not None and target_table!='':
    df_remote = dataframe.create_dataframe_from_pandas(connection_context = conn, 
                                                   pandas_df = df_data, 
                                                   table_name = target_table,
                                                   schema = service_schema,
                                                   force = True,
                                                   disable_progressbar = True)

    st.write(f'Successful creation of the table {target_table}: {conn.has_table(table=target_table, schema = service_schema)}')

requirements.txt

包含所需模块的文件,这些模块将从PyPI中提取。

cfenv
hana-ml
streamlit

runtime.txt

该文件定义了要使用的Python版本。相应版本的CloudFoundry buildpack将被下载。

python-3.9.*

请注意.* 的使用,它可以确保使用 Python 3.9 的最新可用 buildpck。

程序文件

该文件定义了应用程序启动时要执行的命令。

web: streamlit run loadfile_mvp.py --server.port ${PORT}

请注意变量${PORT}的使用,它确保streamlit应用在CloudFoundry应用的默认Web端口上运行。

manifest.yml

应用程序的清单。

---
applications:
- name: ((app-name))
  routes:
    - route: ((app-name))-((account-name)).cfapps.((btp-region)).hana.ondemand.com
  memory: 2048M
  buildpacks: 
    - python_buildpack
  env:
    STREAMLIT_SERVER_MAX_UPLOAD_SIZE: 100
  services:
  - hdb-staging-schema

请注意。

  1. hdb-staging-schemaa 服务实例的绑定。
  2. 传递Streamlit的环境变量STREAMLIT_SERVER_MAX_UPLOAD_SIZE ,以限制上传文件的大小。
  3. 使用变量来避免硬编码应用程序名称、账户名称(用于为您的部署创建唯一的URL)以及部署应用程序的BTP区域。这些变量是通过一个单独的文件vars.yml ,如下所述。

vars.yml

该文件包含清单文件的变量。

app-name: csv2hdb
account-name: e8ee8684trial
btp-region: us10

您应修改这三个变量以符合您的应用程序的要求。

部署应用程序

要部署应用程序,请使用。

cf push --vars-file vars.yml

你应该看到一个类似于下面的日志。

Pushing app csv2hdb to org e8ee8684trial / space dev as witalij... ...
Applying manifest file /.../sap-tech-bytes/scripts/manifest.yml...
Manifest applied
Packaging files to upload...
Uploading files...
 1.89 KiB / 1.89 KiB [=========================================================================================================================================] 100.00% 1s

Waiting for API to complete processing files...

Staging app and tracing logs...
   Downloading python_buildpack...
   Downloaded python_buildpack
   Cell d5f8ba8f-6b80-4d41-b335-1a257634845d creating container for instance e4c343c7-2922-43d4-a6a0-b7055e4ab8a7
   Cell d5f8ba8f-6b80-4d41-b335-1a257634845d successfully created container for instance e4c343c7-2922-43d4-a6a0-b7055e4ab8a7
   Downloading app package...
   Downloaded app package (1.9K)
   -----> Python Buildpack version 1.7.49
   -----> Supplying Python
   -----> Installing python 3.9.9
   Copy [/tmp/buildpacks/49b223c631091864eee2a117ec43f025/dependencies/15b399819fce43a5b5eedb0316dbb3c1/python_3.9.9_linux_x64_cflinuxfs3_6a29c275.tgz]
   Using python's pip module
...
   -----> Running Pip Install
   Collecting cfenv
   Downloading cfenv-0.5.3-py2.py3-none-any.whl (4.5 kB)
   Collecting hana-ml
   Downloading hana_ml-2.13.22060800-py3-none-any.whl (5.1 MB)
   Collecting streamlit
   Downloading streamlit-1.10.0-py2.py3-none-any.whl (9.1 MB)
...
   Exit status 0
   Uploading droplet, build artifacts cache...
   Uploading droplet...
   Uploading build artifacts cache...
   Uploaded build artifacts cache (127.7M)
   Uploaded droplet (201.5M)
   Uploading complete
...

Waiting for app csv2hdb to start...

Instances starting...

name:                csv2hdb
requested state:     started
isolation segment:   trial
routes:              csv2hdb-e8ee8684trial.cfapps.us10.hana.ondemand.com
last uploaded:       Thu 09 Jun 12:55:08 CEST 2022
stack:               cflinuxfs3
buildpacks:
...
	name               version   detect output   buildpack name
	python_buildpack   1.7.49    python          python

type:            web
sidecars:
instances:       1/1
memory usage:    2048M
start command:   streamlit run loadfile_mvp.py --server.port ${PORT}
     state     since                  cpu    memory         disk         details
#0   running   2022-06-09T10:55:34Z   0.0%   106.1M of 2G   751M of 1G

应用程序正在运行,我们可以从命令行中看到它...

cf app csv2hdb

...以及在SAP BTP Cockpit中。