背景
Salesforce のファイルを外部から取り出したい、と言う要望はままあるのですが、Python ライブラリの Simple Salesforce を活用した実装の参考例です。
ダウンロードしたいファイルの ContentVersion レコードの Id がわかるならば手っ取り早いのですが、往々にして ContentDocumentId しかわからない事が多いので、ContentDocumentId から紐解く処理にしています。
エラー処理を全く考慮しておらず、そのまま業務使用することは想定しておりませんので、あらかじめご了承ください。
環境
- 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)
実行結果
実行環境にもよりますが、次のように実行フォルダにファイルが生成されていれば成功です。
応用する事で、特定のレコードに添付されたファイルをすべてダウンロードしたりもできるようになるでしょう。
以上、Salesforce のファイルをダウンロードする Python コード (Simple Salesforce 利用)、でした。