# Pythonによる添付ファイル付きレコードの作成

**URL:** <https://community.cybozu.dev/t/topic/243>\
**Category:** kintone 開発相談\
**Created:** [2017 年 1 月 31 日午前 3:49 UTC](https://community.cybozu.dev/t/topic/243 "2017-01-31T03:49:24Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Legacy\_Account1519](https://avatars.discourse-cdn.com/v4/letter/l/a3d4f5/32.png) [@Legacy\_Account1519](https://community.cybozu.dev/u/Legacy_Account1519)\
**Post date:** [2017 年 1 月 31 日午前 3:49 UTC](https://community.cybozu.dev/t/topic/243/1 "2017-01-31T03:49:24Z")

</div>

[Pythonによるファイルのアップロード](https://community.cybozu.dev/hc/ja/community/posts/115000229966-Python%E3%81%AB%E3%82%88%E3%82%8B%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E3%81%AE%E3%82%A2%E3%83%83%E3%83%97%E3%83%AD%E3%83%BC%E3%83%89) で、fileKeyの取得ができましたので、添付ファイルにするまでのコードを書きました。

&nbsp;

#!/usr/bin/python

# coding:utf-8

import requests  
import json

URL = “[https://xxxxx.cybozu.com:443](https://xxxxx.cybozu.com:443)” # kintoneのサブドメイン([xxx.cybozu.com](http://xxx.cybozu.com))  
APP\_ID = “17” # kintoneのアプリID  
API\_TOKEN = “APP TOKEN” # kintoneのAPIトークン  
KNT\_PASS = “xxxxxx” # ログインネーム:パスワード をbase64でエンコード

#KINTONEアプリのフィールドコード  
#添付ファイル Attch

class KINTONE:  
&nbsp; &nbsp; def UploadToKintone(self, url, knt\_pass,path,filename):  
&nbsp; &nbsp; img = open(path + filename, ‘rb’)  
&nbsp; &nbsp; files={‘file’:(filename,img,‘image/jpeg’)}  
&nbsp; &nbsp; headers = {“X-Cybozu-Authorization”: knt\_pass , ‘X-Requested-With’: ‘XMLHttpRequest’}  
&nbsp; &nbsp; resp=requests.post(url+“/k/v1/file.json”,files=files,headers=headers)

&nbsp; &nbsp; return resp

def PostToKintone(self,url,appId,apiToken,filekey):  
&nbsp; &nbsp; record = {  
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; “Attch”:{‘type’:“FILE”,“value” :[{‘fileKey’:filekey}]}  
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; #他のフィールドにデータを挿入する場合は’,‘で区切る  
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }  
&nbsp; &nbsp; data = {‘app’:appId,‘record’:record}  
&nbsp; &nbsp; headers = {“X-Cybozu-API-Token”: apiToken, “Content-Type” : “application/json”}  
&nbsp; &nbsp; resp=requests.post(url+’/k/v1/record.json’,json=data,headers=headers)

&nbsp; &nbsp; return resp

if \_\_name\_\_ == ‘\_\_main\_\_’:  
&nbsp; &nbsp; Path=‘/tmp/’ #ファイル保存パス  
&nbsp; &nbsp; FileName=‘image.jpg’ #ファイル名

&nbsp; &nbsp; knt=KINTONE()  
&nbsp; &nbsp; resp=knt.UploadToKintone(URL, KNT\_PASS,Path,FileName)

&nbsp; &nbsp; txt=json.loads(resp.text)  
&nbsp; &nbsp; FileKey=txt[‘fileKey’]  
&nbsp; &nbsp; resp=knt.PostToKintone(URL, APP\_ID, API\_TOKEN,FileKey)  
&nbsp; &nbsp; print resp.text
