LoginSignup
3
5

More than 5 years have passed since last update.

Python requestsモジュールを使用してKINTONEに添付ファイル付きレコードを作成する

Last updated at Posted at 2017-01-31

フロー

  1. KINTONEで入れ物を作る
  2. Pythonで添付ファイルを送信する
    • fileKeyを取得する
    • レコードに結合する
  3. うれしい

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"}

となり幸せな気分になりました。

3
5
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
3
5