1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Salesforce のファイルをダウンロードする Python コード (Simple Salesforce 利用)

Posted at

背景

Salesforce のファイルを外部から取り出したい、と言う要望はままあるのですが、Python ライブラリの Simple Salesforce を活用した実装の参考例です。

ダウンロードしたいファイルの ContentVersion レコードの Id がわかるならば手っ取り早いのですが、往々にして ContentDocumentId しかわからない事が多いので、ContentDocumentId から紐解く処理にしています。

:warning: エラー処理を全く考慮しておらず、そのまま業務使用することは想定しておりませんので、あらかじめご了承ください。

環境

  • pip 追加インストール
    • python-dotenv==1.0.0
    • requests==2.31.0
    • simple-salesforce==1.12.5
  • python 3.11.5

コード

まず.envファイルを作成し、Salesforce にログインするユーザー名とパスワードを設定します。(変数名はコード内を参照)
また、次のコードの最初にある contentDocumentId にダウンロードしたいファイルの ContentDocumentId をセットしてください。

# ダウンロードしたいファイルの ContentDocumentId をセットします
contentDocumentId = '[対象ファイルの ContentDocumentId]'

# .env の Salesforce のユーザー名/パスワードを環境変数化
from dotenv import load_dotenv
load_dotenv('./.env')

import os
import requests
from simple_salesforce import Salesforce

# 環境変数から Salesforce のユーザー名/パスワードを読み込みセット
SALESFORCE_USERNAME = os.environ.get('SALESFORCE_USERNAME')
SALESFORCE_PASSWORD = os.environ.get('SALESFORCE_PASSWORD')

# Salesforce へログイン
sf = Salesforce(username=SALESFORCE_USERNAME,password=SALESFORCE_PASSWORD, security_token='')

# 該当する ContentVersion のレコードを取得
query = f"SELECT Id, PathOnClient FROM ContentVersion WHERE isLatest = True AND ContentDocumentId = '{contentDocumentId}'"
results = sf.query(query)

# ダウンロード用の URL を組み立て
url = f"https://{sf.sf_instance}{results['records'][0]['attributes']['url']}/VersionData"
print(url)

# ファイル名をセット
fileName = results['records'][0]['PathOnClient']
print(fileName)

# requests を使ってファイルを取得
response = requests.get(url=url, headers={'Authorization': 'OAuth ' + sf.session_id, 'Content-Type': 'application/octet-stream'})

# 成功すれば実行フォルダにファイルを作成
if response.ok:
    with open(fileName, 'wb') as f:
        f.write(response.content)

ちなみに、対象ファイルの ContentDocumentId は URL から見つけるのが手っ取り早いです。(069 から始まる 18 桁の Id)
ContentDocumentIdの見方.png

実行結果

実行環境にもよりますが、次のように実行フォルダにファイルが生成されていれば成功です。
SimpleSalesforceFileDownload.png

応用する事で、特定のレコードに添付されたファイルをすべてダウンロードしたりもできるようになるでしょう。
以上、Salesforce のファイルをダウンロードする Python コード (Simple Salesforce 利用)、でした。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?