### Seatable Metadata Structure Example - JSON Source: https://developer.seatable.com/scripts/python/objects/metadata An example of the JSON output structure returned by the get_metadata() function. This structure details the tables, columns (with their types, names, and properties), and views (including filters, sorts, and group settings) of a Seatable base. ```json { "tables": [{ "_id": "4krH", "name": "Contact", "is_header_locked": False, "columns": [{ "key": "0000", "type": "text", "name": "Name", "editable": True, "width": 200, "resizable": True, "draggable": True, "data": None, "permission_type": "", "permitted_users": [] }, { "key": "M31F", "type": "text", "name": "Email", "editable": True, "width": 200, "resizable": True, "draggable": True, "data": None, "permission_type": "", "permitted_users": [] }], "views": [{ "_id": "0000", "name": "Default view", "type": "table", "is_locked": False, "filter_conjunction": "And", "filters": [], "sorts": [], "groupbys": [], "group_rows": [], "groups": [], "colorbys": {}, "hidden_columns": [], "rows": [], "formula_rows": {}, "link_rows": {}, "summaries": {}, "colors": {} }] }] } ``` -------------------------------- ### Install SeaTable API Python Package Source: https://developer.seatable.com/scripts/python/common_questions This command installs the `seatable-api` Python package, which is required for running SeaTable scripts locally. This package provides the necessary functions to interact with the SeaTable API. ```shell pip3 install seatable-api ``` -------------------------------- ### List Installed Python Packages in SeaTable Cloud Source: https://developer.seatable.com/scripts/python/common_questions This Python script queries and prints the names of all installed packages within the SeaTable cloud environment. This is useful for identifying available third-party libraries and ensuring compatibility with your scripts. ```python import importlib.metadata # List all installed packages installed_packages = importlib.metadata.distributions() # Print package names for package in installed_packages: print(package.metadata['Name']) ``` -------------------------------- ### Python Authentication with API Token (SeaTable Editor) Source: https://developer.seatable.com/scripts/python/introduction Demonstrates authentication using an API token within SeaTable's integrated Python editor. It utilizes the 'context' object to automatically provide credentials, simplifying the setup. The Base object is initialized and authenticated. ```python from seatable_api import Base, context base = Base(context.api_token, context.server_url) base.auth() ``` -------------------------------- ### Get User Info from Seatable API Source: https://developer.seatable.com/scripts/python/objects/users Retrieves the name and ID of a user from the Seatable API. It requires a unique username (e.g., 'user@auth.local') as input and returns a dictionary containing 'id_in_org' and 'name'. Ensure the `seatable_api` library is installed. ```python from seatable_api import Base, context base = Base(context.api_token, context.server_url) base.auth() user_info = base.get_user_info("aea9e807bcfd4f3481d60294df74f6ee@auth.local") print(user_info) ``` -------------------------------- ### Access API Token in Python Source: https://developer.seatable.com/scripts/python/objects/context Illustrates how to obtain the API token using 'context.api_token'. This token is required for authenticating API requests to access a Seatable base. The example prints the token. ```python from seatable_api import context print(context.api_token) ``` -------------------------------- ### Get Base Source: https://developer.seatable.com/scripts/python/objects/accounts Retrieves a specific base by its name from a given workspace. The base must be authorized for access. ```APIDOC ## GET /account/get_base ### Description Get the base named `base_name` in the workspace whose id is `workspace_id`. You'll be able to interact with this base using all the `base` methods presented in this manual. Please note that the base is authorized. ### Method GET ### Endpoint /account/get_base ### Parameters #### Query Parameters - **workspace_id** (integer) - Required - The ID of the workspace. - **base_name** (string) - Required - The name of the base to retrieve. ### Request Example ```python from seatable_api import Account username = 'xxx@email.com' password = 'xxxxxxx' server_url = 'https://cloud.seatable.io/' account = Account(username, password, server_url) account.auth() base = account.get_base(35, 'new-base') print(base.get_metadata()) ``` ### Response #### Success Response (200) - **base object** - A base object that allows further interaction with the base. #### Response Example (Output is a base object, with specific structure depending on the base's metadata) ``` -------------------------------- ### Get File Upload Link using SeaTable API (Detailed Method) Source: https://developer.seatable.com/scripts/python/objects/files Obtains a pre-signed upload link from the SeaTable server, which is required for the detailed two-step file upload process. This method returns a dictionary containing the `upload_link`, `parent_path`, `img_relative_path`, and `file_relative_path`. It uses the `seatable_api` library and requires authentication. ```python from seatable_api import Base, context base = Base(context.api_token, context.server_url) base.auth() try: # Get the upload link and file path allocated by server upload_link_dict = base.get_file_upload_link() upload_link = upload_link_dict['upload_link'] parent_dir = upload_link_dict['parent_path'] file_relative_path = upload_link_dict['file_relative_path'] img_relative_path = upload_link_dict['img_relative_path'] print("Successfully obtained upload link details:") print(f"Upload Link: {upload_link}") print(f"Parent Directory: {parent_dir}") print(f"File Relative Path: {file_relative_path}") print(f"Image Relative Path: {img_relative_path}") # Note: The actual file upload using the obtained link would be a separate step using requests.post except Exception as e: print(f"Error obtaining upload link: {e}") ``` -------------------------------- ### Download All Files from a Column - Python Source: https://developer.seatable.com/scripts/python/objects/files Provides an example of iterating through files in a 'File' type column for a specific row in a SeaTable table and downloading each file to a designated local directory. This involves fetching row data and then using `download_file` for each file found. ```python from seatable_api import Base server_url = 'https://cloud.seatable.io' api_token = '5e165f8b7af...98950b20b022083' base = Base(api_token, server_url) base.auth() target_row = base.get_row('Table1','Pd_pHLM8SgiEcnFW5I7HLA') save_directory = './tmp/' files = target_row['File'] print(f"{len(files)} files to download") for file in files : print(f"Downloading {file['url']}") base.download_file(file['url'], save_directory + file['name']) ``` -------------------------------- ### Date and Time Utility Functions Overview (Python) Source: https://developer.seatable.com/scripts/python/objects/date-utils Demonstrates common date and time operations using the dateutils module, including getting the current datetime, adding dates, extracting date parts, calculating date differences, and handling timezone-aware strings. Supports ISO format for input and output. ```python from seatable_api.date_utils import dateutils dt_now = dateutils.now() # 2025-09-30 15:47:00 # 1. date 10 days after dt_now dt_10_days = dateutils.dateadd(dt_now, 10) # 2025-10-10 15:47:00 # 2. month 10 days after dt_now dt_month_10_days = dateutils.month(dt_10_days) # 10 # 3. difference between 2 days dt_10_days_before = dateutils.dateadd(dt_now, -10) date_df = dateutils.datediff(dt_10_days_before, dt_10_days, unit="D") # 20 # 4. handle the time string with time-zone info with local timezone of "Asia/Shanghai" (UTC+8) time_str = "2025-07-17T21:57:41+08:00" time_day = dateutils.day(time_str) # 17 time_month = dateutils.month(time_str) # 7 time_year = dateutils.year(time_str) # 2025 time_hour = dateutils.hour(time_str) # 15 (! if local timezone is UTC+2 !) time_minute = dateutils.minute(time_str) # 57 time_date = dateutils.date(time_year, time_month, time_day) # 2025-07-17 ``` -------------------------------- ### Listen for Specific SeaTable Database Events (Python) Source: https://developer.seatable.com/scripts/python/objects/communication-utils This example shows how to listen for specific SeaTable database events, such as table updates (`UPDATE_DTABLE`) or new notifications (`NEW_NOTIFICATION`), using WebSockets. It defines a callback function (`on_update`) to process incoming data and registers it with the SeaTable SocketIO client. The script then waits for events. ```python import json from seatable_api import Base from seatable_api.constants import UPDATE_DTABLE server_url = 'https://cloud.seatable.io' api_token = 'c3c75dca2c369849455a39f4436147639cf02b2d' def on_update(data, index, *args): try: operation = json.loads(data) print(operation) op_type = operation['op_type'] table_id = operation['table_id'] row_id = operation['row_id'] # ... do something except Exception as e: print(e) base = Base(api_token, server_url) base.auth(with_socket_io=True) base.socketIO.on(UPDATE_DTABLE, on_update) base.socketIO.wait() ``` -------------------------------- ### Access DateQuarter Properties Source: https://developer.seatable.com/scripts/python/objects/date-utils Demonstrates accessing properties of a DateQuarter object, including year, quarter number, start date, and end date. Also shows how to generate all dates within a quarter. Requires a DateQuarter object as input. ```python from seatable_api.date_utils import dateutils q = dateutils.quarter_from_yq(2025, 3) q.year q.quarter q.start_date q.end_date list(q.days()) ``` -------------------------------- ### Get SeaTable View by Name (Python) Source: https://developer.seatable.com/scripts/python/objects/views Retrieves a specific view from a SeaTable table by its name. It requires the table name and view name as input. The output is a dictionary representing the view, or an error if the view or table does not exist. ```python from seatable_api import Base, context base = Base(context.api_token, context.server_url) base.auth() view = base.get_view_by_name('Table1', 'Default View') print(view) ``` -------------------------------- ### Get File Download Link (Two-Step Method) - Python Source: https://developer.seatable.com/scripts/python/objects/files Shows how to obtain a temporary, public download link for a file using its 'file path' (the part of the URL after the base UUID). This method is useful for handling large files or slow connections, as it separates link generation from the actual download using standard HTTP requests. ```python from seatable_api import Base, context import requests # Assuming base and context are initialized and authenticated # Example initialization: # base = Base(context.api_token, context.server_url) # base.auth() # file_path is the location within the SeaTable file system, e.g., '/files/2020-10/invoice.pdf' file_path = "/files/2020-10/invoice.pdf" # Get the temporary download link # download_link = base.get_file_download_link(file_path) # Now you can use requests to download the file using the generated link # response = requests.get(download_link, stream=True) # if response.status_code == 200: # with open("/tmp/invoice_downloaded.pdf", 'wb') as f: # for chunk in response.iter_content(chunk_size=8192): # f.write(chunk) # else: # print(f"Failed to get download link or download file: {response.status_code}") ``` -------------------------------- ### Access User ID in Organization in Python Source: https://developer.seatable.com/scripts/python/objects/context Demonstrates how to get the user's ID within the organization using 'context.current_id_in_org'. This ID can be managed by administrators in the web interface. The example prints this ID. ```python from seatable_api import context print(context.current_id_in_org) ``` -------------------------------- ### Flexible Authorization for Local and Cloud Python Scripts Source: https://developer.seatable.com/scripts/python/common_questions This code snippet demonstrates how to configure a Python script to run seamlessly in both local and cloud SeaTable environments by dynamically providing server URL and API token. It utilizes the `seatable_api` library and checks for the `context` object provided in the cloud environment, falling back to manually specified values for local execution. ```python from seatable_api import Base, context server_url = context.server_url or 'https://cloud.seatable.io' api_token = context.api_token or 'c3c75dca2c369848455a39f4436147639cf02b2d' base = Base(api_token, server_url) base.auth() ``` -------------------------------- ### Get Table Metadata Source: https://developer.seatable.com/scripts/python/objects/metadata Retrieves the complete metadata of a table, including its structure, columns, and views, but not the actual row data. ```APIDOC ## GET /api/metadata ### Description Retrieves the complete metadata of a table. The metadata includes information about tables, views, and columns, but does not contain the concrete rows of the table. ### Method GET ### Endpoint /api/metadata ### Parameters #### Query Parameters - **table_id** (string) - Required - The unique identifier of the table for which to retrieve metadata. ### Request Example ``` base.get_metadata(table_id='your_table_id') ``` ### Response #### Success Response (200) - **tables** (array) - An array of table objects, each containing its structure, columns, and views. - **_id** (string) - The unique identifier of the table. - **name** (string) - The name of the table. - **is_header_locked** (boolean) - Indicates if the table header is locked. - **columns** (array) - An array of column objects. - **key** (string) - The unique key of the column. - **type** (string) - The data type of the column (e.g., 'text', 'number'). - **name** (string) - The name of the column. - **editable** (boolean) - Indicates if the column is editable. - **width** (integer) - The width of the column. - **resizable** (boolean) - Indicates if the column is resizable. - **draggable** (boolean) - Indicates if the column is draggable. - **data** (any) - Additional data associated with the column. - **permission_type** (string) - The permission type for the column. - **permitted_users** (array) - A list of users permitted to access the column. - **views** (array) - An array of view objects. - **_id** (string) - The unique identifier of the view. - **name** (string) - The name of the view. - **type** (string) - The type of the view (e.g., 'table', 'gallery'). - **is_locked** (boolean) - Indicates if the view is locked. - **filter_conjunction** (string) - The conjunction used for filtering (e.g., 'And', 'Or'). - **filters** (array) - An array of filter objects. - **sorts** (array) - An array of sort objects. - **groupbys** (array) - An array of groupby objects. - **group_rows** (array) - An array of grouped row objects. - **groups** (array) - An array of group objects. - **colorbys** (object) - Configuration for color-based grouping. - **hidden_columns** (array) - An array of hidden column identifiers. - **rows** (array) - An array of row objects (typically empty for metadata). - **formula_rows** (object) - Formula definitions for rows. - **link_rows** (object) - Link definitions for rows. - **summaries** (object) - Summary configurations for columns. - **colors** (object) - Color configurations for rows or cells. #### Response Example ```json { "tables": [ { "_id": "4krH", "name": "Contact", "is_header_locked": false, "columns": [ { "key": "0000", "type": "text", "name": "Name", "editable": true, "width": 200, "resizable": true, "draggable": true, "data": null, "permission_type": "", "permitted_users": [] }, { "key": "M31F", "type": "text", "name": "Email", "editable": true, "width": 200, "resizable": true, "draggable": true, "data": null, "permission_type": "", "permitted_users": [] } ], "views": [ { "_id": "0000", "name": "Default view", "type": "table", "is_locked": false, "filter_conjunction": "And", "filters": [], "sorts": [], "groupbys": [], "group_rows": [], "groups": [], "colorbys": {}, "hidden_columns": [], "rows": [], "formula_rows": {}, "link_rows": {}, "summaries": {}, "colors": {} } ] } ] } ``` ``` -------------------------------- ### Python Authentication with Account Object Source: https://developer.seatable.com/scripts/python/introduction Illustrates authentication using an account object, which requires username, password, and server URL. This method grants access to all bases associated with the account. It then demonstrates how to retrieve a specific base using its workspace ID and name. ```python from seatable_api import Account account = Account(username, password, server_url) account.auth() base = account.get_base(workspace_id, base_name) ``` -------------------------------- ### Get User Info API Source: https://developer.seatable.com/scripts/python/objects/users Retrieves the name and ID of a user based on their unique username. The username must be in the format 'unique_identifier@auth.local'. ```APIDOC ## GET /users/info ### Description Retrieves the name and ID of a user. The username provided must be a unique identifier ending with `@auth.local`. ### Method GET ### Endpoint `/users/info` #### Query Parameters - **username** (string) - Required - The unique username of the user (e.g., 'aea9e807bcfd4f3481d60294df74f6ee@auth.local'). ### Request Example ```python from seatable_api import Base, context base = Base(context.api_token, context.server_url) base.auth() user_info = base.get_user_info("aea9e807bcfd4f3481d60294df74f6ee@auth.local") print(user_info) ``` ### Response #### Success Response (200) - **id_in_org** (string) - The unique ID of the user within the organization. - **name** (string) - The name of the user. #### Response Example ```json { "id_in_org": "some_user_id", "name": "User Name" } ``` ``` -------------------------------- ### Sending Emails via SMTP in Python Source: https://developer.seatable.com/scripts/python/examples/send_email Demonstrates sending emails using Python's `smtplib`. Includes options for standard SMTP, SMTP with SSL, and SMTP with STARTTLS. Handles authentication and potential exceptions. Requires configured SMTP server details. ```python # 6. Send the email # option a) Sending the email using SMTP try: with smtplib.SMTP() as email_server: email_server.connect(SMTP_SERVER) email_server.login(USERNAME, PASSWORD) email_server.send_message(msg) email_server.quit() except smtplib.SMTPAuthenticationError: print("SMTP User authentication error, Email not sent!") except Exception as e: print(f"SMTP exception {e}") ''' # option b) Sending the email using SMTP / SSL ssl_context = ssl.create_default_context() try: with smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT, context=ssl_context) as email_server: email_server.login(USERNAME, PASSWORD) email_server.send_message(msg) email_server.quit() except smtplib.SMTPAuthenticationError: print("SMTP User authentication error, Email not sent!") except Exception as e: print(f"SMTP exception {e}") # option c) Sending the email using SMTP with STARTTLS try: with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as email_server: email_server.starttls() email_server.login(USERNAME, PASSWORD) email_server.send_message(msg) email_server.quit() except smtplib.SMTPAuthenticationError: print("SMTP User authentication error, Email not sent!") except Exception as e: print(f"SMTP exception {e}") ''' ``` -------------------------------- ### Python Authentication with API Token (Local Execution) Source: https://developer.seatable.com/scripts/python/introduction Shows how to authenticate with an API token when running Python scripts locally. This method requires explicitly defining the API token and server URL. It bypasses the 'context' object, which is unavailable in local environments. Best practices advise against hardcoding credentials. ```python from seatable_api import Base API_TOKEN = 'c3c75dca2c369848455a39f4436147639cf02b2d' SERVER_URL = 'https://cloud.seatable.io' base = Base(API_TOKEN, SERVER_URL) base.auth() ``` -------------------------------- ### Add Table to SeaTable Base with Python Source: https://developer.seatable.com/scripts/python/objects This Python code snippet demonstrates how to add a new table to an existing SeaTable base. It requires the 'seatable_api' library and uses the 'Base' object to connect and authenticate. The function takes a table name and a list of column definitions as input. The output is a new table in the specified base. ```python from seatable_api import Base, context base = Base(context.api_token, context.server_url) base.auth() columns=[ { "column_type" : "text", "column_name": "name" }, { "column_type": "number", "column_name": "age" } ] base.add_table("ScriptTest", lang='en', columns=columns) ``` -------------------------------- ### Generate DateQuarters within a Range Source: https://developer.seatable.com/scripts/python/objects/date-utils Returns a generator yielding DateQuarter objects between a start and end date. The last quarter can be optionally included. Takes start date, end date, and an optional boolean for including the last quarter as input. ```python from seatable_api.date_utils import dateutils qs1 = dateutils.quarters_within("2024-03-28", "2025-07-17") print(list(qs1)) qs2 = dateutils.quarters_within("2024-03-28", "2025-07-17", include_last=True) print(list(qs2)) ``` -------------------------------- ### Get Table Metadata - Python Source: https://developer.seatable.com/scripts/python/objects/metadata Retrieves the complete metadata for a specific table within a Seatable base. This function returns the structure of the table, including its columns and views, but does not include the actual data rows. It requires authentication with the Seatable API. ```python from seatable_api import Base, context base = Base(context.api_token, context.server_url) base.auth() print(base.get_metadata()) ``` -------------------------------- ### Import Seatables-api and Datetime Libraries in Python Source: https://developer.seatable.com/scripts/python/introduction Imports the necessary Base and context functions from the seatable-api library along with the datetime module. This is a prerequisite for interacting with SeaTable bases using Python scripts, especially within the SeaTable Python Pipeline. ```python from seatable_api import Base, context from datetime import datetime ``` -------------------------------- ### month Source: https://developer.seatable.com/scripts/python/objects/date-utils Returns the month of a given date. The month number starts at 1. ```APIDOC ## month ### Description Return the month of a given `date`. The month number starts at 1, like when writing a date. ### Method `dateutils.month(date)` ### Parameters - **date** (string/datetime) - The date to extract the month from. ### Request Example ```python from seatable_api.date_utils import dateutils dateutils.month("2025-5-4") # 5 ``` ### Response Example (Returns the month as an integer.) ``` -------------------------------- ### List Views Source: https://developer.seatable.com/scripts/python/objects/views Retrieves all views associated with a specific table. This is useful for getting an overview of all available views in a table. ```APIDOC ## GET /api/views/{table_name} ### Description Retrieves all views for the table named `table_name`. ### Method GET ### Endpoint `/api/views/{table_name}` ### Parameters #### Path Parameters - **table_name** (string) - Required - The name of the table to list views from. ### Response #### Success Response (200) - **views** (array) - A list of view objects, where each object represents a view in the table. #### Response Example ```json { "views": [ { "_id": "0000", "name": "Default View", "type": "table", "is_locked": false, "rows": [], "formula_rows": {}, "summaries": [], "filter_conjunction": "And", "sorts": [], "filters": [], "hidden_columns": [], "groupbys": [], "group_rows": [], "groups": [] }, { "_id": "0001", "name": "Gallery View", "type": "gallery", "is_locked": false, "rows": [], "formula_rows": {}, "summaries": [], "filter_conjunction": "And", "sorts": [], "filters": [], "hidden_columns": [], "groupbys": [], "group_rows": [], "groups": [] } ] } ``` ### Request Example ```python from seatable_api import Base, context base = Base(context.api_token, context.server_url) base.auth() views = base.list_views('Table1') print(views) ``` ``` -------------------------------- ### SeaTable File Download API Source: https://developer.seatable.com/scripts/python/objects/files This section covers the methods for downloading files from SeaTable. It includes a simple one-step download and a more detailed two-step method for complex scenarios. ```APIDOC ## Download Files This section details how to download files from SeaTable using the provided API. ### File URL Structure The general structure for accessing files is: `{server_url}/workspace/{workspace_id}/asset-preview/{base_uuid}/{file location}` - `{server_url}`: The URL of your SeaTable server (e.g., `https://cloud.seatable.io`). - `{workspace_id}`: Found in database URLs or user manuals. - `{base_uuid}`: The unique identifier for your base, found in Team administration or page source. - `{file location}`: The path to the file within the base. This can be under `/files/`, `/images/`, or `/custom/` followed by subdirectories. ### Simple One-Step Download This method downloads a file directly to a local path. #### Method `base.download_file(file_url, save_path)` #### Parameters - **file_url** (string) - Required - The full URL of the file to download. - **save_path** (string) - Required - The local path where the file will be saved. #### Response - Nothing (throws an error if the URL is invalid or the save path is wrong). #### Example ```python from seatable_api import Base, context base = Base(context.api_token, context.server_url) base.auth() file_url = "https://cloud.seatable.io/workspace/74/asset-preview/41cd05da-b29a-4428-bc31-bd66f4600817/files/2020-10/invoice.pdf" save_path = "/tmp/invoice.pdf" base.download_file(file_url, save_path) ``` ### Download All Files from a Column This example shows how to download all files from a specific column in a table. #### Method Iterate through files in a row's column and use `base.download_file()`. #### Example ```python from seatable_api import Base server_url = 'https://cloud.seatable.io' api_token = 'YOUR_API_TOKEN' base = Base(api_token, server_url) base.auth() target_row = base.get_row('Table1','ROW_ID') save_directory = './tmp/' files = target_row['FileColumnName'] print(f"{len(files)} files to download") for file in files : print(f"Downloading {file['url']}") base.download_file(file['url'], save_directory + file['name']) ``` ### Detailed Two-Step Download This method is useful for large files or slow connections. It involves getting a temporary download link and then making a GET request. #### Step 1: Get Download Link ##### Method `base.get_file_download_link(file_path)` ##### Parameters - **file_path** (string) - Required - The "file location" part of the URL (e.g., `/files/YYYY-MM/file.pdf` or `/custom/folder/file.pdf`). ##### Response - The public download link (e.g., `{server_url}/seafhttp/files/{access_token}/{file_name}`). This link expires. ##### Example ```python from seatable_api import Base, context import requests # Assuming base is already initialized and authenticated # base = Base(context.api_token, context.server_url) # base.auth() file_path = "/files/2020-10/invoice.pdf" download_link = base.get_file_download_link(file_path) print(f"Download Link: {download_link}") # Step 2: Download the file using the link response = requests.get(download_link, stream=True) if response.status_code == 200: with open("/tmp/invoice.pdf", 'wb') as f: for chunk in response.iter_content(chunk_size=8192): f.write(chunk) print("File downloaded successfully.") else: print(f"Failed to download file. Status code: {response.status_code}") ``` ### Notes on Download Links - Download links generated by `get_file_download_link` are temporary and expire after a few hours. - For permanent file storage and direct use in web pages, it's recommended to use external public hosting services and store only the links in SeaTable. ``` -------------------------------- ### Get Year from Date Source: https://developer.seatable.com/scripts/python/objects/date-utils Extracts and returns the year from a given date string. It takes a date string as input. ```python from seatable_api.date_utils import dateutils dateutils.year("2030-1-1") ``` -------------------------------- ### List Seatable Workspaces and Bases with Python Source: https://developer.seatable.com/scripts/python/objects/accounts This function retrieves all workspaces accessible by the authenticated account, including their bases, tables, and shared views. It requires the seatable_api library and account credentials. The output is a dictionary containing a 'workspace_list'. ```python from seatable_api import Account import json username = 'xxx@email.com' password = 'xxxxxxx' server_url = 'https://cloud.seatable.io/' account = Account(username, password, server_url) account.auth() workspaces = account.list_workspaces() print(json.dumps(workspaces, indent='\u2002')) ``` -------------------------------- ### Download File (One-Step Method) - Python Source: https://developer.seatable.com/scripts/python/objects/files Demonstrates how to download a file directly to a local path using the `download_file` method from the SeaTable Python API. This method requires the full file URL and the desired local save path. It handles the download in a single operation. ```python from seatable_api import Base, context base = Base(context.api_token, context.server_url) base.auth() file_url = "https://cloud.seatable.io/workspace/74/asset-preview/41cd05da-b29a-4428-bc31-bd66f4600817/files/2020-10/invoice.pdf" save_path = "/tmp/invoice.pdf" base.download_file(file_url, save_path) ``` -------------------------------- ### Synchronize MySQL Data to SeaTable using Python Source: https://developer.seatable.com/scripts/python/examples/sync_mysql This script connects to both MySQL and SeaTable, retrieves data, compares records based on a 'name' field, and appends new records from MySQL to the specified SeaTable. It requires the `pymysql` and `seatable_api` libraries. Configuration variables for database credentials and table/column names are provided at the beginning of the script. ```python import pymysql from seatable_api import Base, context """ This Python script facilitates the synchronization of data from a MySQL database to a SeaTable table, ensuring consistency and updating records seamlessly. """ # SeaTable base config SERVER_URL = context.server_url or 'http://127.0.0.1:8000' API_TOKEN = context.api_token or '...' # SeaTable table config ST_TABLE_NAME = 'Sync MySQL' ST_NAME_COLUMN = 'Name' # MySQL config HOST = 'localhost' USER = 'username' PASSWORD = 'topsecret' MYSQL_DB = 'seatable' MYSQL_TABLE = 'order' MYSQL_NAME_COLUMN = 'name' def sync_mysql(): # 1. Initialize connection # 1. a) SeaTable authentication base = Base(API_TOKEN, SERVER_URL) base.auth() # 1. b) MySQL connection connection = pymysql.connect(host=HOST, user=USER, password=PASSWORD, db=MYSQL_DB) # 2. Fetch existing rows from seaTable rows = base.list_rows(ST_TABLE_NAME) row_keys = [row.get(ST_NAME_COLUMN) for row in rows] # 3. Retrieving data from MySQL with connection.cursor(pymysql.cursors.DictCursor) as cursor: sql = "SELECT * FROM " + MYSQL_TABLE cursor.execute(sql) mysql_data = cursor.fetchall() # Synchronization rows_data = [] for item in mysql_data: # 4. Look for data from MySQL not present in SeaTable if item.get(MYSQL_NAME_COLUMN) not in row_keys: row_data = { ST_NAME_COLUMN: item.get(MYSQL_NAME_COLUMN), } # 5. Eventually add missing records if rows_data : base.batch_append_rows(TABLE_NAME, rows_data) if __name__ == '__main__': sync_mysql() ``` -------------------------------- ### months Source: https://developer.seatable.com/scripts/python/objects/date-utils Calculates the difference in months between two given dates. The result can be negative if the end date is before the start date. ```APIDOC ## months ### Description Return the months difference between two given date. The result can be negative if `end` is before `start`. ### Method `dateutils.months(start, end)` ### Parameters - **start** (string/datetime) - The start date. - **end** (string/datetime) - The end date. ### Request Example ```python from seatable_api.date_utils import dateutils dateutils.months("2024-5-1","2025-5-4") # 12 ``` ### Response Example (Returns the difference in months as an integer.) ``` -------------------------------- ### Copy Base Source: https://developer.seatable.com/scripts/python/objects/accounts Copies an existing base from a source workspace to a destination workspace. ```APIDOC ## POST /account/copy_base ### Description Copy the base `base_name` from the workspace whose id is `src_workspace_id` to the workspace whose id is `dst_workspace_id`. ### Method POST ### Endpoint /account/copy_base ### Parameters #### Query Parameters - **src_workspace_id** (integer) - Required - The ID of the source workspace. - **base_name** (string) - Required - The name of the base to copy. - **dst_workspace_id** (integer) - Required - The ID of the destination workspace. ### Request Example ```python from seatable_api import Account username = 'xxx@email.com' password = 'xxxxxxx' server_url = 'https://cloud.seatable.io/' account = Account(username, password, server_url) account.auth() base_metadata = account.copy_base(35, 'My Base', 74) print(base_metadata) ``` ### Response #### Success Response (200) - **Dict** - A dictionary containing the metadata of the newly created base in the destination workspace. #### Response Example ```json { "name": "My Base", "id": "...", "tables": [...], "group_shared_dtables": [], "group_shared_views": [], "folders": [] } ``` ``` -------------------------------- ### hours Source: https://developer.seatable.com/scripts/python/objects/date-utils Calculates the difference in hours between two given datetimes. The result can be negative if the end datetime is before the start datetime. ```APIDOC ## hours ### Description Return the hours difference between two given datetime. The result can be negative if `end` is before `start`. ### Method `dateutils.hours(start, end)` ### Parameters - **start** (string/datetime) - The start datetime. - **end** (string/datetime) - The end datetime. ### Request Example ```python from seatable_api.date_utils import dateutils dateutils.hours("2019-6-3 20:01:12", "2020-5-3 13:13:13") # 8009 ``` ### Response Example (Returns the difference in hours as an integer.) ``` -------------------------------- ### days Source: https://developer.seatable.com/scripts/python/objects/date-utils Calculates the difference in days between two given dates. The result can be negative if the end date is before the start date. ```APIDOC ## days ### Description Return the days difference between two given date. The result can be negative if `end` is before `start`. ### Method `dateutils.days(start, end)` ### Parameters - **start** (string/datetime) - The start date. - **end** (string/datetime) - The end date. ### Request Example ```python from seatable_api.date_utils import dateutils dateutils.days('2024-6-1', '2025-5-15') # 348 ``` ### Response Example (Returns the difference in days as an integer.) ``` -------------------------------- ### Convert HEIC to PNG and Upload to SeaTable Source: https://developer.seatable.com/scripts/python/examples/heic_to_png This script automates the conversion of HEIC image files to PNG format and uploads the converted files back into a specified SeaTable base. It requires the 'pillow_heif', 'Pillow', and 'seatable_api' libraries. The script authenticates with SeaTable, downloads HEIC files from a designated column, converts them to PNG using Pillow, and then uploads the PNG files back to SeaTable, updating a result column with the new file URLs. ```python import requests from PIL import Image from pillow_heif import register_heif_opener from seatable_api import Base, context # Activate heif/heic support register_heif_opener() TABLE_NAME = "Convert images" FILE_COLUMN = "HEIC" RESULT_COLUMN = "PNG" # 1. Authentication base = Base(context.api_token, context.server_url) base.auth() for row in base.list_rows(TABLE_NAME): if row.get(FILE_COLUMN) is None: continue # 2. Download heic image url = row.get(FILE_COLUMN)[0] filename_heic = url.split('/')[-1] base.download_file(url, filename_heic) # 3. Transform image to png im = Image.open(filename_heic) filename_png = f'image-{row["_id"]}.png' im.save(filename_png, quality=90) print('Saved image') # 4.a) Upload info_dict = base.upload_local_file(filename_png, name=None, file_type='image', replace=True) print('Uploaded file') # 4.b) Save back to SeaTable Base img_url = info_dict.get('url') base.update_row(TABLE_NAME, row['_id'], {RESULT_COLUMN: [img_url]}) print('Stored image info in base') ``` -------------------------------- ### Get View by Name Source: https://developer.seatable.com/scripts/python/objects/views Retrieves a specific view from a table by its name. This function is useful when you need to access the details of a single, known view. ```APIDOC ## GET /api/views/{view_name} ### Description Retrieves a specific view of the table `table_name`, identified by its name `view_name`. ### Method GET ### Endpoint `/api/views/{table_name}/{view_name}` ### Parameters #### Path Parameters - **table_name** (string) - Required - The name of the table containing the view. - **view_name** (string) - Required - The name of the view to retrieve. ### Response #### Success Response (200) - **view** (object) - A dictionary representing the view object. - **_id** (string) - The unique identifier of the view. - **name** (string) - The name of the view. - **type** (string) - The type of the view (e.g., 'table'). - **is_locked** (boolean) - Indicates if the view is locked. - **rows** (array) - List of rows in the view. - **formula_rows** (object) - Formula rows configuration. - **summaries** (array) - Summary configurations for the view. - **filter_conjunction** (string) - The conjunction used for filters (e.g., 'And'). - **sorts** (array) - Sorting configurations for the view. - **filters** (array) - Filtering configurations for the view. - **hidden_columns** (array) - List of hidden column names. - **groupbys** (array) - Grouping configurations for the view. - **group_rows** (array) - Grouped rows configuration. - **groups** (array) - Group configurations. #### Response Example ```json { "_id": "0000", "name": "Default View", "type": "table", "is_locked": false, "rows": [], "formula_rows": {}, "summaries": [], "filter_conjunction": "And", "sorts": [], "filters": [], "hidden_columns": [], "groupbys": [], "group_rows": [], "groups": [] } ``` ### Request Example ```python from seatable_api import Base, context base = Base(context.api_token, context.server_url) base.auth() view = base.get_view_by_name('Table1', 'Default View') print(view) ``` ``` -------------------------------- ### Send Email Script in Python Source: https://developer.seatable.com/scripts/python/examples/send_email This Python script demonstrates sending emails via SMTP using the smtplib module. It constructs MIME objects for rich content emails, creates HTML content from 'long text' columns using the markdown module, and retrieves configuration parameters from the SeaTable database. The script handles recipient fetching, subject retrieval, email body composition (plain text, HTML, or database-sourced), and optional file attachments. ```python import markdown import smtplib, ssl from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.header import Header from urllib import parse import requests from seatable_api import Base, context """ This Python script demonstrates sending emails via SMTP using the smtplib module and constructing MIME objects to compose rich content emails within SeaTable. """ # SeaTable API authentication base = Base(context.api_token, context.server_url) base.auth() CONFIG_TABLE = 'Send email config' CONTACTS_TABLE = 'Contacts' # SMTP server configurations for sending emails SMTP_SERVER = 'my.smtpserver.com' SMTP_PORT = 465 USERNAME = 'my.em@il.com' PASSWORD = 'topsecret' SENDER = 'My name' # 1. Get email configuration from the 'Send email config' table current_row = context.current_row or base.list_rows(CONFIG_TABLE)[0] # Choose RECIPIENT_EMAIL between "hard-coded" (addresses l.48 of this script) # or "database" (get emails from 'Email' column in the 'Contacts' table) RECIPIENT_EMAIL = current_row.get('Recipient email') # Choose SUBJECT between "hard-coded" (subject l.57 of this script) # or "database" (get subject from 'Subject' column in the 'Send email config' table) SUBJECT_SOURCE = current_row.get('Subject source') # Choose EMAIL_FORMAT between "text" (hard-coded plain text, defined l.71), # "html" (hard-coded HTML, defined l.77) # and "database" (content of the 'Email body' column in the 'Send email config' table) EMAIL_FORMAT = current_row.get('Email format') # If Attach file, the script retrieves the first file from the 'File' column of the 'Sending email config' ATTACH_FILE = current_row.get('Attach file') ``` -------------------------------- ### Extract Month from Date (Python) Source: https://developer.seatable.com/scripts/python/objects/date-utils Retrieves the month component from a given date string. The month is represented as a number starting from 1. ```python from seatable_api.date_utils import dateutils dateutils.month("2025-5-4") # 5 ``` -------------------------------- ### Get Weekday from Date (Python) Source: https://developer.seatable.com/scripts/python/objects/date-utils Returns the day of the week for a given date. The result is an integer from 0 to 6, where Monday is 0 and Sunday is 6. ```python from seatable_api.date_utils import dateutils dateutils.weekday("2025-6-2") # 0 (June 2, 2025 was a Monday) ``` -------------------------------- ### Real-time Data Updates via WebSockets in SeaTable (Python) Source: https://developer.seatable.com/scripts/python/objects/communication-utils This code snippet demonstrates how to establish a WebSocket connection to SeaTable to receive real-time notifications about database updates. It utilizes the 'websocket-client' library (recommended but not strictly required) and authenticates with an API token and server URL. The script then waits for incoming messages. ```python from seatable_api import Base server_url = 'https://cloud.seatable.io' api_token = 'c3c75dca2c369849455a39f4436147639cf02b2d' base = Base(api_token, server_url) base.auth(with_socket_io=True) base.socketIO.wait() ``` -------------------------------- ### Get Current ISO Date (Python) Source: https://developer.seatable.com/scripts/python/objects/date-utils Returns the current date formatted as an ISO string (YYYY-MM-DD). This function is useful for daily tracking or reporting. ```python from seatable_api.date_utils import dateutils today = dateutils.today() print(today) # 2025-09-30 ```