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 5 years have passed since last update.

Kintone アプリのレコードの作成日時を変更?してみる。

Posted at

0.はじめに

Kintone アプリのレコードの作成日時を変更?してみる。としましたが…、

以下のページにもある様に、登録済みのレコードの作成日時は変更出来ない仕様みたいなので、

正確には、レコードの作成日時を指定して、新たに登録し直す。

になります。

今回は、上記機能の Python スクリプトを作成してみました。

1.Python スクリプト

Kintone_replicateRecords.py
#!/usr/bin/python
# -*- coding: utf-8 -*-

# ---1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----

# ==============================================================================
#
# Kintone_replicateRecords.py
#
# ==============================================================================

# kintone REST APIの共通仕様 – cybozu developer network
# https://developer.cybozu.io/hc/ja/articles/201941754-kintone-REST-API%E3%81%AE%E5%85%B1%E9%80%9A%E4%BB%95%E6%A7%98
# レコードの登録(POST) – cybozu developer network
# https://developer.cybozu.io/hc/ja/articles/202166160

import sys
import os
import logging
import codecs
import json
import datetime
import requests
import time

sys.stdout = codecs.getwriter('utf_8')(sys.stdout)

logging.basicConfig(level=logging.DEBUG,
    format="[%(asctime)s] %(levelname)-8s %(filename)-20.20s (%(lineno)06d) %(funcName)-12.12s | %(message)s",
    datefmt='%Y-%m-%d %H:%M:%S',
    filename=(__file__ + ".log"),
    filemode='w')

sh = logging.StreamHandler()
sh.setLevel(logging.DEBUG)
formatter = logging.Formatter("[%(asctime)s] %(levelname)-8s (%(lineno)06d) | %(message)s")
sh.setFormatter(formatter)
logging.getLogger().addHandler(sh)

logging.debug("<<<<<<<< %s Start >>>>>>>>", __file__)

# ------------------------------------------------------------------------------
# Constant
# ------------------------------------------------------------------------------
# cybozu.com
Cybozu_Url_Base = 'https://****.cybozu.com'

Src_App_ID = [移行元のKintoneアプリID]
Src_API_Token = '[移行元のKintoneアプリのAPIトークン]'
Src_Fields = [
    'AAA',
    'BBB',
    'CCC',
    'DDD']

Dst_App_ID = [移行先のKintoneアプリID]
Dst_API_Token = '[移行先のKintoneアプリのAPIトークン]'
Dst_Fields = Src_Fields

Base_DateTime = datetime.datetime(2000, 1, 1, 0, 0, 0)

# ------------------------------------------------------------------------------
# Variables
# ------------------------------------------------------------------------------

# ------------------------------------------------------------------------------
# Function
# ------------------------------------------------------------------------------

def replicateRecords():
    """Get Cybozu Monitors"""
    logging.debug("==== Replicate Records ====")
    logging.debug("==== Get Source Records ====")
    source_records = requests.get(Cybozu_Url_Base + '/k/v1/records.json',
        headers = {
            'X-Cybozu-API-Token' : Src_API_Token,
            'Content-Type' : 'application/json; charset=UTF-8',
            'If-Modified-Since' : 'Thu, 01 Jun 1970 00:00:00 GMT'
        },
        data = json.dumps({
            'app': Src_App_ID,
            'query': '$id > 0 order by $id asc limit 500',
            'fields': ['$id'] + Src_Fields,
            'totalCount': 'true'
        })
    )
    source_records_json = source_records.json()['records']
    logging.debug("source_records_json:[%s]", json.dumps(source_records_json, ensure_ascii=False))
    logging.debug("====")
    for n, k in enumerate(sorted(source_records_json, key=lambda x:int(x[u'$id']['value']))):
        logging.debug("(%04d/%04d) Source Record | [%s] ",
            n + 1, len(source_records_json), json.dumps(k, ensure_ascii=False, sort_keys=True))
        logging.debug("==== Post Destination Record ====")
        record = {}
        for nn, dst_field in enumerate(Dst_Fields):
            record[dst_field.decode('utf-8')] = {
                "value": k[Src_Fields[nn].decode('utf-8')]['value']
            }
        dt = Base_DateTime + datetime.timedelta(minutes=n)
        dt_str = "{0:%Y-%m-%dT%H:%M:%SZ}".format(dt)
        record['作成日時'.decode('utf-8')] = {
            "value": dt_str.decode('utf-8')
        }
        record['更新日時'.decode('utf-8')] = {
            "value": dt_str.decode('utf-8')
        }
        logging.debug("(%04d/%04d) Destination Record | [%s] ",
            n + 1, len(source_records_json),
            json.dumps(record, ensure_ascii=False))
        resp = requests.post(Cybozu_Url_Base + "/k/v1/record.json",
            headers = {
                'X-Cybozu-API-Token' : Dst_API_Token,
                'Content-Type' : 'application/json; charset=UTF-8',
                'If-Modified-Since' : 'Thu, 01 Jun 1970 00:00:00 GMT'
            },
            json = {
                'app': Dst_App_ID,
                'record': record
            }
        )
        logging.debug("resp:[%s]", resp)

# ------------------------------------------------------------------------------
# Program Start
# ------------------------------------------------------------------------------
if __name__ == '__main__':

    replicateRecords()

# ------------------------------------------------------------------------------
# Program End
# ------------------------------------------------------------------------------

logging.debug("<<<<<<<< %s End >>>>>>>>", __file__)

# ---1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----

  1. 定数定義
    • Cybozu_Url_Base : ※任意 (ex : https://****.cybozu.com)
    • Src_App_ID : [移行元のKintoneアプリID]
    • Src_API_Token : [移行元のKintoneアプリのAPIトークン]
    • Src_Fields : ※移行元のKintoneアプリのレコードの各フィールドコードのリスト
    • Dst_App_ID : [移行先のKintoneアプリID]
    • Dst_API_Token : [移行先のKintoneアプリのAPIトークン]
    • Dst_Fields : ※移行先のKintoneアプリのレコードの各フィールドコードのリスト
  2. 注意事項
    • 今回の Python スクリプトでは、2000/01/01 00:00 から1分ずつ追加した作成日時を設定しています。
      • 69行目 : Base_DateTime = datetime.datetime(2000, 1, 1, 0, 0, 0)
      • 108行目 : dt = Base_DateTime + datetime.timedelta(minutes=n)
      • 109行目 : dt_str = "{0:%Y-%m-%dT%H:%M:%SZ}".format(dt)
    • レコード番号の制御はしていません。
    • Src_Fields と Dst_Fields の順番は合わせる必要があります。

99.ハマりポイント

XX.まとめ

作成日時を変更したい時もありますよね。

ということで、参考になれば♪

🙇‍♂️🙇‍♂️🙇‍♂️

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?