feishu_insert.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. """
  2. feishu python方法
  3. """
  4. import requests
  5. def get_app_token():
  6. """
  7. 获取飞书api token
  8. :return:
  9. """
  10. url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/"
  11. post_data = {
  12. "app_id": "cli_a51114cf8bf8d00c", # 这里账号密码是发布应用的后台账号及密码
  13. "app_secret": "cNoTAqMpsAm7mPBcpCAXFfvOzCNL27fe",
  14. }
  15. response = requests.request("POST", url=url, data=post_data)
  16. tenant_access_token = response.json()["tenant_access_token"]
  17. return tenant_access_token
  18. class FeishuInsert(object):
  19. """
  20. feishu Python Object
  21. """
  22. def __init__(self, document_token):
  23. self.headers = {"Content-Type": "application/json"}
  24. self.document_token = document_token
  25. def insert_value(self, sheet_id, ranges, values):
  26. """
  27. 在表的某一个sheet的ranges中插入数据,若该地方存在数据,会自动把已有的数据往下移动,再写如数据
  28. :param sheet_id: 飞书表的唯一ID
  29. :param ranges: 单元格位置的range, 从左上角到右下角, 两边都是闭区间
  30. :param values: 二维数组, 用于填充ranges的空格数组
  31. """
  32. insert_value_url = "https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{}/values_prepend".format(
  33. self.document_token)
  34. # print(get_app_token())
  35. headers = {
  36. "Authorization": "Bearer " + get_app_token(),
  37. 'contentType': 'application/json; charset=utf-8'
  38. }
  39. body = {
  40. "valueRange": {
  41. "range": "{}!{}".format(sheet_id, ranges),
  42. "values": values
  43. }
  44. }
  45. response = requests.request("POST", url=insert_value_url, headers=headers, json=body)
  46. print(response.json())