フロー
- KINTONEで入れ物を作る
- Pythonで添付ファイルを送信する
- fileKeyを取得する
- レコードに結合する
- うれしい
KITONEの入れ物
フィールドコードが"Attch"の添付ファイルの入れ物を作ります。
Pythonで添付ファイルを送信する
KINTONEでレコードにファイルを添付するには、
- ファイルをアップロード
- レコードと結合
という手順を踏みます。
それをPythonで書くと↓
#!/usr/bin/python
# coding:utf-8
import requests
import json
URL = "https://xxxxx.cybozu.com:443" # kintoneのサブドメイン(xxx.cybozu.com)
APP_ID = "ID" # kintoneのアプリID
API_TOKEN = "APP TOKEN" # kintoneのAPIトークン
KNT_PASS = "xxxxxx" # ログインネーム:パスワード をbase64でエンコード
#KINTONEアプリのフィールドコード
#添付ファイル Attch
class KINTONE:
def UploadToKintone(self, url, knt_pass,path,filename):
img = open(path + filename, 'rb')
files={'file':(filename,img,'image/jpeg')}
headers = {"X-Cybozu-Authorization": knt_pass , 'X-Requested-With': 'XMLHttpRequest'}
resp=requests.post(url+"/k/v1/file.json",files=files,headers=headers)
return resp
def PostToKintone(self,url,appId,apiToken,filekey):
record = {
"Attch":{'type':"FILE","value" :[{'fileKey':filekey}]}
#他のフィールドにデータを挿入する場合は','で区切る
}
data = {'app':appId,'record':record}
headers = {"X-Cybozu-API-Token": apiToken, "Content-Type" : "application/json"}
resp=requests.post(url+'/k/v1/record.json',json=data,headers=headers)
return resp
if __name__ == '__main__':
Path='/tmp/' #ファイル保存パス
FileName='image.jpg' #ファイル名
knt=KINTONE()
resp=knt.UploadToKintone(URL, KNT_PASS,Path,FileName)
txt=json.loads(resp.text)
FileKey=txt['fileKey']
resp=knt.PostToKintone(URL, APP_ID, API_TOKEN,FileKey)
print resp.text
アウトプットは
{"id":"1","revision":"1"}
となり幸せな気分になりました。