笔记:While all of these scripts have been tested and found to be fully functional, due to the vast amount of potential use cases, Anaplan does not explicitly support custom scripts built by our customers. This article is for information only and does not suggest any future product direction.

入门

Python 3提供了许多与API互动的选择。本文将解释如何使用Python 3来自动化我们的养蜂场中可用的许多请求,可以在https://anaplan.docs.apiary.io/#

本文假设您已安装了请求(版本2.18.4),Base64和JSON模块,以及Python 3版本3.6.4。请确保您正在使用Python 3安装这些模块,而不是较旧版本的Python。有关这些模块的更多信息,请参阅其各自的网站:

  • Python(If you are using a Python version older or newer than 3.6.4, or requests version older or newer than 2.18.4, we cannot guarantee the validity of the article.)
  • Requests
  • Base Converter
  • JSON(Note: Install instructions are not at this site but will be the same as any other Python module.)

笔记:Please read the comments at the top of every script before use, as they more thoroughly detail the assumptions that each script makes.

Authentication

To start, let's talk about Authentication. Every script run that connects to our API will be required to supply valid authentication. There are two ways to authenticate a Python script that I will be covering.

  1. 证书身份验证
  2. 基本编码身份验证

证书身份验证将要求您拥有有效的Anaplan证书,您可以阅读有关该证书的更多信息here。一旦您在本地保存证书后,以正确转换Anaplan证书以适用于API,首先您需要OpenSSL。一旦拥有,您将需要通过在终端中运行以下代码将证书转换为PEM格式:

openssl x509 -inform der -in certificate-(certnumber).cer -out certtest.pem

如果您使用证书授权,我们在本文中使用的脚本将假定您知道与证书关联的Anaplan帐户电子邮件。如果您不知道,可以通过在终端中运行以下代码来从PEM文件中提取通用名称(CN):

openssl x509 -text -in certtest.pem

To be used with the API, the PEM certificate string will need to be converted to base64, but the scripts we will be covering will take care of that for you, so I won't cover that in this section.

要使用基本身份验证,您将需要了解正在使用的Anaplan帐户电子邮件以及密码。本文中的所有脚本将在顶部附近具有以下代码:

# Insert the Anaplan account email being used username = '' ----------------- # If using cert auth, replace cert.pem with your pem converted certificate # filename. Otherwise, remove this line. cert = open('cert.pem').read() # If using basic auth, insert your password. Otherwise, remove this line. password = '' # Uncomment your authentication method (cert or basic). Remove the other. user = 'AnaplanCertificate ' + str(base64.b64encode(( f'{username}:{cert}').encode('utf-8')).decode('utf-8')) # user = 'Basic ' + str(base64.b64encode((f'{username}:{password}' # ).encode('utf-8')).decode('utf-8')

无论使用身份验证方法,您都需要将用户名变量设置为正在使用的Anaplan帐户电子邮件。

如果您使用证书进行身份验证,则需要将PEM转换为同一文件夹或您正在运行的脚本的文件夹中。如果您的证书在子文件夹中,请记住在更换CERT.PEM时包括文件路径(例如CERT/CERT.PEM)。您可以删除密码行及其注释及其各自的用户变量。

If you are using basic authentication, you will need to set the password variable to your Anaplan account password, and you can remove the cert line, its comments, and its respective user variable.

Getting the Information Needed for Each Script

本文涵盖的大多数脚本将要求您知道您正在尝试处理的文件,操作等的ID或元数据。每个获取此信息的脚本都标题为get_____.py。For example, if you want to get your file's metadata, you'll rungetfiles.py,它将在选定模型,选定的工作区,阵列中为JSON文件中的每个文件编写文件元数据files.json。You can then open the JSON file, find the file you need to reference, and use the metadata from that entry in your other scripts.

提示:If you open the raw data tab of the JSON file it makes it much easier to copy the whole set of metadata.

以下是下载的链接get____.py脚本。每个得到脚本使用requests.getmethod to send a get request to the proper API endpoint.

  • 得到Workspaces.py:Writes an array toworkspaces.json在用户可以访问的所有工作区中。
  • 得到Models.py:Writes an array to模特of either all the models a user has access to ifwguidis left blank or all of the models the user has access to in a selected workspace if a workspace ID was inserted.
  • 得到ModelInfo.py:Writes an array tomodelinfo.json与所选模型关联的所有元数据。
  • getfiles.py:Writes an array tofiles.jsonof all metadata for each file the user has access to in the selected model and workspace. (Please refer to养蜂场有关私人与默认文件的更多信息。通常,建议所有脚本通过同一用户帐户运行。)
  • 得到ChunkData.py:Writes an array tochunkdata.jsonof all metadata for each chunk of the selected file in the selected model and workspace.
  • getimports.py:Writes an array toimports.jsonof all metadata for each import in the selected model and workspace.
  • 得到出口。py:Writes an array toexports.json所选模型和工作区中每个导出的所有元数据。
  • getactions.py:Writes an array toactions.jsonof all metadata for all actions in the selected model and workspace.
  • 得到过程。py:Writes an array toprocess.jsonof all metadata for all processes in the selected model and workspace.

Uploads

A file can be uploaded to the Anaplan API endpoint either in chunks or as a single chunk. Per our apiary:

We recommend that you upload files in several chunks. This enables you to resume an upload that fails before the final chunk is uploaded. In addition, you can compress files on the upload action. We recommend compressing single chunks that are larger than 50MB. This creates a Private File.

笔记:上传一个文件使用的API,文件必须存在t in Anaplan. If the file has not been previously uploaded, you must upload it initially using the Anaplan user interface. You can then carry out subsequent uploads of that file using the API.

多个块上传

这script we have for reference is built so that if the script is interrupted for any reason, or if any particular chunk of a file fails to upload, simply rerunning the script will start uploading the file again, starting at the last successful chunk. For this to work, the file must be initially split using a standard naming convention, using the terminal script below.

split -b [numberofBytes] [path and filename] [prefix for output files]

You can store the file in any location as long as you the proper file path when setting thechunkFilePrefix(e.g.chunkfileprefix =''upload_chunks/块 - ”这将寻找名称的文件块大块,,,,,,,,大块etc., up to在文件夹中script_origin/upload_chunks/。您不太可能超越)。这将使脚本知道在哪里查找文件的块要上传。您可以下载脚本以从此链接运行多个块上传:chunkupload.py。

笔记:假定的命名约定只有在使用Terminal,如果使用Windows中的另一种方法将文件分开,则它们不一定会起作用。如果您使用的是Windows,则需要创建一种方法来标准化块的命名{chunkFilePrefix}(aa - zz)或运行脚本如在蜂房

笔记:chunkupload.pyscript keeps track of the last successful chunk by writing the name of the last successful chunk to a .txt filechunkStop.txt。This file is deleted once the import completes successfully. If the file is modified in between runs of the script, the script may not function correctly. Best practice is to leave the file alone and delete it if you want to start the upload from the first chunk.

Single Chunk Upload

仅当文件足够小以在合理的时间范围内上传时,才应使用单个块上传。如果上传失败,则必须从一开始就重新开始。如果您的文件具有不同的名称,则其版本的服务器的名称,您将需要修改行31("name" : '')反映本地文件的名称。该脚本将单个PUT请求运行到API端点以上传文件。您可以下载以从此链接运行单个块上传的脚本:singleChunkUpload.py

进口

import.py脚本将发布请求发送到所选导入的API端点。您需要将导入值设置为导入的元数据。看Getting the Information Needed for Each Script想要查询更多的信息。您可以下载以从此链接运行导入的脚本:Import.py.

导入完成后,脚本将在数组中为导入任务编写元数据Postimport.json,您可以使用哪些任务来验证要查看运行时的状态importStatus.py脚本。这importStatus.py脚本将返回与所选expertid及其各自列表索引相关的所有任务的列表。如果您想检查上一次运行导入的状态,请确保您正在检查Postimport.jsonto verify you have the correct taskID. Enter the index for the task and the script will write the task status to an array in fileimportStatus.json。如果任务仍在进行中,它将打印任务状态和进度。如果任务完成和故障转储可用,它将以逗号分隔格式写入失败转储importDump.csv可用于审查失败的原因。If the task finished with no failures, you will get a message telling you the import has completed with no failures. You can download the script forimportStatus.py从此链接:importStatus.py

笔记:If you check the status of a task with an old taskID for an import that has been run since you last checked it, the dump will no longer exist andimportDump.csv将被HTTP错误覆盖,任务的状态将为410 Gone

出口

export.py脚本将发布请求发送到所选导出的API端点。您需要将导出值设置为导出的元数据。看Getting the Information Needed for Each Script想要查询更多的信息。您可以下载脚本running an export from this link:Export.py

导出完成后,脚本将在数组中为导出任务编写元数据Postexport.json,您可以使用哪些任务来验证要查看运行时的状态exportstatus.py脚本。这exportstatus.py脚本将返回与所选exportid关联的所有任务及其各自列表索引的列表。如果您想检查上一次运行导入的状态,请确保您正在检查Postexport.jsonto verify you have the correct taskID. Enter the index for the task and the script will write the task status to an array in fileexportStatus.json。如果任务仍在进行中,它将打印任务状态和进度。重要的是要注意,如果导出失败,将不会生成故障转储。您可以下载脚本exportstatus.py从此链接:exportstatus.py

动作

action.pyscript sends a post request to the API endpoint for the selected action (for use with actions other than imports or exports). You will need to set the actionData value to the metadata for the action. SeeGetting the Information Needed for Each Script想要查询更多的信息。您可以下载脚本以从此链接中运行操作:ActionStatus.py

过程

process.pyscript sends a post request to the API endpoint for the selected process. You will need to set the processData value to the metadata for the process. SeeGetting the Information Needed for Each Script想要查询更多的信息。您可以下载脚本running a process from this link:process.py。

该过程完成后,脚本将在数组中为过程任务编写元数据后进程,您可以使用哪些任务来验证要查看运行时的状态processStatus.py脚本。这processStatus.pyscript will return a list of all tasks associated with the selected processID and their respective list index. If you are wanting to check the status of the last run import, make sure you are checking后进程to verify you have the correct taskID. Enter the index for the task and the script will write the task status to an array in fileProcessStatus.json。如果任务仍在进行中,它将打印任务状态和进度。如果任务完成和故障转储可用,它将以逗号分隔格式写入失败转储ProcessDump.CSV可用于审查失败的原因。重要的是要注意,只有在该过程中的一个导入失败时,该过程本身不会生成故障转储。如果任务没有失败完成,您将收到一条消息,告诉您该过程已经完成而没有失败。您可以下载脚本processStatus.py从此链接:processStatus.py.

下载文件

从Anaplan API端点下载文件将在端点上存在的许多块中下载文件。重要的是要注意,您应该设置变量文件名name它在文件元数据中具有。首先,下载单个块元数据将以一个数组写成downloadChunkData.jsonfor reference. The script will then download the file chunk by chunk and write each chunk to a new local file with the same name as the 'name' listed in the file's metadata. You can download the link for this script from this link:downloadfile.py。

笔记:如果文件已经与您的脚本相同的文件夹中存在,则名称与namevalue in the file's metadata, the local file will be overwritten with the file being downloaded from the server.

删除文件

You can delete the file contents of any file that the user has access to that exists in the Anaplan server.笔记:这只会删除私人内容。默认内容和导入数据源模型对象将保留。You can download the link for this script from this link:deletefile.py。

Standalone Requests Code and Their Required Headers

In this section, I will list the code for each request detailed above, including the API URL and the headers necessary to complete the call. I will be leaving the content right of授权:headers blank. Authorization header values can be either基本Encoded_username:密码oranaplancertificate encoded_commonname:pem_certificate_string(看证书授权 - 使用的Anaplan-Api有关编码证书的更多信息)

笔记:requests.getwill only generate a response body from the server, and no data will be locally saved unless written to a local file.

获取工作区列表

requests.get(“https://api.anaplan.com/1/3/workspaces/', headers='Authorization':)

Get Models List

requests.get('https://api.anaplan.com/1/3/models/',headers = {'授权':})或requests.get('https://api.anaplan.com/1/3/workspaces/{wguid}/models',headers = {'授权':})

Get Model Info

requests.get(f'https://api.anaplan.com/1/3/models/{mGuid}', headers={'Authorization':})

获取文件/导入/导出/操作/进程列表

这得到request for files, imports, exports, actions, or processes is largely the same. Changefilesto imports, exports, actions, or processes to run each.

requests.get('https://api.anaplan.com/1/3/workspaces/ {wguid}/models/{mguid}/files',headers = {'授权':})

获取块数据

requests.get('https://api.anaplan.com/1/3/workspaces/ {wguid}/models/{mguid}/files/{fileid}/chunks',headers = {'授权':})

Post Chunk Count

requests.post('https://api.anaplan.com/1/3/workspaces/{wGuid}/models/{mGuid}/files/{fileID}/chunks/{chunkNumber}', headers={'Authorization': , 'Content-type': 'application/json'}, json={fileMetaData})

Upload a Chunk of a File

requests.put('https://api.anaplan.com/1/3/workspaces/ {wguid}/models/{mguid}/files/{fileid}/chunks/chunks/{chunknumber}',headers = {'授权':,'content-type':'application/offer-stream'},data = {local块文件的原始内容})

Mark an upload complete

requests.put('https://api.anaplan.com/1/3/workspaces/ {wguid}/models/{mguid}/files/{fileid}/complete'content-type':'application/json'},json = {filemetadata})

将文件上传到一个块中

requests.put('https://api.anaplan.com/1/3/workspaces/ {wguid}/models/{mguid}/files/{fileid}',headers = {'prounterization':':,'content-'content-type':'application/offet-stream'},data = {本地文件的原始内容})

运行进口/导出/流程

这post request for imports, exports, and processes are largely the same. Changeimports出口,动作或流程以运行每个。

requests.post('https://api.anaplan.com/1/3/workspaces/{wGuid}/models/{mGuid}/imports/{Id}/tasks', headers={'Authorization': , 'Content-Type': 'application/json'}, data=json.dumps({'localeName': 'en_US'}))

Run an Action

requests.post('https://api.anaplan.com/1/3/workspaces/ {wguid}/models/{mguid}/imports/imports/imports/{id}/tasks',data = {'localEname':'en_us':'en_us'},标题= {'授权':,'content-type':'application/json'})

Get Task list for an Import/Export/Action/Process

获取导入,导出,操作和过程任务列表的请求基本相同。改变importsto exports, actions, or processes to get each task list.

requests.get(“https://api.anaplan.com/1/3/workspaces/{wGuid}/models/{mGuid}/imports/{importID}/tasks', headers={'Authorization':})

获取进口/导出/操作/过程任务的状态

获取导入,导出,操作和过程任务状态的请求在很大程度上是相同的。改变importsto exports, actions, or processes to get each task list.笔记:只有导入和流程才会产生故障转储。

requests.get('https://api.anaplan.com/1/3/workspaces/ {wguid}/models/{mguid}/imports/imports/{id}/tasks/taskid/{taskid}'headers = {'授权{'授权':})

下载一个文件

笔记:You will need to get the chunk metadata for each chunk of a file you want to download.

requests.get('https://api.anaplan.com/1/3/workspaces/ {wguid}/models/{mguid}/files/{fileid}/chunks/chunks/{chunkid},headers = {'propureition = {'授权':,'Accept':'application/offet-stream'})

Delete a File

笔记:这只会删除私人内容。默认内容和导入数据源模型对象将保留。

requests.delete('https://api.anaplan.com/1/3/workspaces/ {wguid}/models/{mguid}/files/files/{fileid}',headers = {'oferationization':,'content-type':'应用程序/json'}

笔记:本文未涵盖SFDC用户管理,但是提供的脚本中相同的概念可以应用于SFDC用户管理。有关SFDC用户管理的更多信息SFDC user administration

这content in this article has not been evaluated for all Anaplan implementations and may not be recommended for your specific situation.
Please consult your internal administrators prior to applying any of the ideas or steps in this article.
Comments

我似乎无法获得链接Getting the Information Needed for Each Script(under the Imports heading) to work, could@chase.hippen确认?

Thanks!

卡勒姆

Version history
Last update:
04-08-202108:38 AM
Updated by:
About the Author
Contributors
标签(1)