123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- """
- @author: luojunhui
- feishu python方法
- """
- import requests
- def get_app_token():
- """
- 获取飞书api token
- :return:
- """
- url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/"
- post_data = {
- "app_id": "cli_a51114cf8bf8d00c", # 这里账号密码是发布应用的后台账号及密码
- "app_secret": "cNoTAqMpsAm7mPBcpCAXFfvOzCNL27fe",
- }
- response = requests.request("POST", url=url, data=post_data)
- tenant_access_token = response.json()["tenant_access_token"]
- print(tenant_access_token)
- return tenant_access_token
- class Feishu(object):
- """
- feishu Python Object
- """
- def __init__(self, document_token):
- self.headers = {"Content-Type": "application/json"}
- self.document_token = document_token
- def prepend_value(self, sheet_id, ranges, values):
- """
- 在表的某一个sheet的ranges中插入数据,若该地方存在数据,会自动把已有的数据往下移动,再写如数据
- :param sheet_id: 飞书表的唯一ID
- :param ranges: 单元格位置的range, 从左上角到右下角, 两边都是闭区间
- :param values: 二维数组, 用于填充ranges的空格数组
- """
- insert_value_url = "https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{}/values_prepend".format(
- self.document_token
- )
- # print(get_app_token())
- headers = {
- "Authorization": "Bearer " + get_app_token(),
- "contentType": "application/json; charset=utf-8",
- }
- body = {
- "valueRange": {"range": "{}!{}".format(sheet_id, ranges), "values": values}
- }
- response = requests.request(
- "POST", url=insert_value_url, headers=headers, json=body
- )
- print(response.json())
- def insert_value(self, sheet_id, ranges, values):
- """
- 插入数据
- :param sheet_id:
- :param ranges:
- :param values:
- :return:
- """
- insert_value_url = (
- "https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{}/values".format(
- self.document_token
- )
- )
- headers = {
- "Authorization": "Bearer " + get_app_token(),
- "contentType": "application/json; charset=utf-8",
- }
- body = {
- "valueRange": {"range": "{}!{}".format(sheet_id, ranges), "values": values}
- }
- response = requests.request(
- "PUT", url=insert_value_url, headers=headers, json=body
- )
- print(response.json())
- def search_value(self, sheet_id, ab):
- """
- 搜索
- :param sheet_id:
- :param ab:
- :return:
- """
- ranges = "{}!{}".format(sheet_id, ab)
- # print(ranges)
- search_url = "https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{}/values/{}".format(
- self.document_token, ranges
- )
- headers = {
- "Authorization": "Bearer " + get_app_token(),
- "contentType": "application/json; charset=utf-8",
- }
- response = requests.request("GET", url=search_url, headers=headers)
- return response.json()
|