Python: Native Methods
Reference for Jestor's Python low-code methods: currentData, beforeSave and afterSave, plus methods for records, users, tasks, files and PDFs.
Python: Native Methods
Reference for Jestor's Python low-code methods: currentData, beforeSave and afterSave, plus methods for records, users, tasks, files and PDFs.
How your code runs
Your code runs on Python 3.12, from top to bottom, every time the trigger or function runs. These names are always available, without imports:
- jestor: the native methods described in this page.
- Filter and Operators: to filter records, users and tasks.
- currentData, beforeSave, afterSave, currentUser, recordData and params: the data of the run (see below). The ones that don't apply to the run are empty dictionaries.
- response(), showMessage(), Type and stopCodeExecution(): to return a value, show a message or stop the save.
Besides the Python standard library, you can import these packages: requests, dateutil (python-dateutil), pandas, openpyxl, markdown, md_to_html, jwt, jwcrypto, qrcode, barcode (python-barcode) and PIL (pillow).
- The native methods take their arguments in a list, e.g.
jestor.count(['table_name', filters]). Leave an optional argument out instead of passing an empty list. - An exception that is not handled fails the run with its message. A native method that fails raises a
JestorApiException, with the error message of Jestor. - Records are read with the permissions of the user who ran the trigger or function.
- A trigger that creates, updates or deletes records runs the triggers of those tables too, up to 5 levels deep: deeper, the save fails with "Max trigger depth reached". A trigger that writes to its own table should only write when a value actually changes, or it runs itself again.
Common variables and dictionaries
Triggers receive three dictionaries with the data sent by the user and the data of the record:
- currentData: the record with the values of this save, including the fields that didn't change. For example, if a user drags a card in a kanban to the "In Progress" stage, currentData['stage'] contains "In Progress". To know if a field changed, compare it with beforeSave, e.g.
currentData['stage'] != beforeSave.get('stage'). Changing currentData has no effect on the record. - beforeSave: the record before the change. For example, if a user drags a card from "New" to "In Progress", currentData['stage'] contains "In Progress" and beforeSave['stage'] contains "New". Bonus: in a synchronous before create or before update trigger, the values you change in beforeSave are saved to the record, e.g.
beforeSave['status'] = 'approved'. - afterSave: the record after the change. In the example above, afterSave['stage'] contains "In Progress". Bonus: some values only exist in afterSave. For example, in an After a record is created trigger, the id of the record is only in afterSave, because it is created when the record is saved.
- currentUser: the user who ran the trigger, with their id_user, email and name.
Two other dictionaries are only present in low-code Functions:
- recordData: the record a Button + Run a function ran on. Connection fields (N:1) bring the first level of the connected record, so its data can be read without a separate search.
- params: the data received when the Function runs through a webhook. For example, for the JSON payload {"status":"New"}, params['status'] contains "New".
Triggers
A trigger runs when a record of its table is created, updated or deleted, before or after the save.
- Synchronous triggers run during the save, and the user waits for them. If one fails, the save fails with its error message. Keep them short, and do slow work, like external requests or changes to many records, in an asynchronous trigger.
- Asynchronous triggers run in the background without holding the save, so they can't change or stop it. In them, stopCodeExecution() sends its message to the user as a notification.
- When a table has more than one trigger for the same event, they run one after the other, and a synchronous trigger receives the beforeSave changes of the previous ones.
- Triggers don't run on draft records. When a draft is saved as a record, the create triggers run.
Field values
The value of a field depends on its type:
- Text and email: str.
- Number, currency and percent: float. A value saved as text can arrive as a str, so convert it with
float(). - Checkbox: bool, or 1 and 0 in update triggers, so test it with
if value:instead of comparing it with True. - Date and date-time: a "YYYY-MM-DD HH:MM:SS" str in triggers. Save them as "YYYY-MM-DD" or "YYYY-MM-DD HH:MM:SS".
- Single selection: the option label in triggers and the option key in get. Save the key (see Get Field Properties): a label that doesn't exist creates a new option.
- Multiple selection and tags: a list of option labels in triggers and of option keys in get.
- Connection (N:1) and user fields: the id of the connected record, often as a str (e.g. "42"), so convert it with
int(). get withfetch_type='full'returns the connected record instead. - Connection (N:N): a list of record ids. Saving a list replaces all the connected records.
- Files: a JSON str with the list of files. Use jestor.file() to change them (see Files).
- Empty fields: None.
In before triggers, currentData has the values as they were sent: a selection can be its label or its key, and a connection its id or name.
Return a value
Call response() to set the value the function returns, e.g. the result of a webhook call. Assigning a variable (e.g. result = ...) does not return it.
total = jestor.count(['orders'])
response({'total': total})showMessage() also sets the returned value, so use one of them in each run: the last call wins.
Create Record
Use the table method with the table name, then the insert method with a dictionary of field names and values. It returns the created record.
The table and field names are the internal names (e.g. clients, due_date), not the labels shown in Jestor.
record = jestor.table('table_name').insert({'name': 'test'})
new_id = record['id_table_name']Edit Record
Use the table method with the table name, then the update method with the record id and a dictionary of the fields to change. It returns the updated record.
record_id = 1
record = jestor.table('table_name').update(record_id, {'name': 'test'})The id of a record is in the id_<table name> field, e.g. afterSave['id_table_name']. update adds this field to the dictionary you pass, so pass a new dictionary in each call.
Delete Record
Use the table method with the table name, then the delete method with the record id.
record_id = 1
jestor.table('table_name').delete(record_id)List Records
Use the table method with the table name, then the get method. It returns a list of records.
records = jestor.table('table_name').get()
filters = [
Filter('name', 'test', 'like', 'string'),
]
records = jestor.table('table_name').get(
filters=filters,
limit=50,
sort='name asc',
fields_to_select=['name', 'email'],
)The get method receives the following parameters:
- filters: a list of Filter (see Filters below). Default: no filters.
- limit: how many records to return, up to 500. Default: 100.
- page: which page of records to return. Default: 1.
- sort: the field and direction to sort by, e.g. "name asc". Without a direction it sorts descending. Default: newest records first.
- fields_to_select: the fields to return, e.g. ['name', 'age', 'email']. Default: all fields.
- fetch_type: "single" returns only the record data, "full" also returns the connected records. Default: "single".
- operator: "AND" or "OR", how the filters are combined. Default: "AND".
To read more than 500 records, read page by page until a page has fewer records than the limit:
records = []
page = 1
while True:
batch = jestor.table('orders').get(limit=500, page=page, fields_to_select=['id_orders', 'total'])
records.extend(batch)
if len(batch) < 500:
break
page += 1Use jestor.user().get() and jestor.fetchTasks() to list users and tasks.
Filters
The Filter object receives the following parameters:
- field: str, the field name.
- value: the value to compare.
- operator: str, one of the operators below.
- type: str, the field type. Default: "string".
The operators are:
- Equal: "=="
- Different: "!="
- Contains: "like"
- Does not contain: "notLike"
- Starts with: "startsWith"
- In a list: "in" (the value is a list)
- Not in a list: "not_in" (the value is a list)
- Is null: "isnull"
- Is not null: "is_not_null"
- Is null or empty: "nullOrEmpty"
- Is filled: "filled"
- Greater than: ">"
- Greater than or equal: ">="
- Less than: "<"
- Less than or equal: "<="
- Between: "between", with the end value in
valueF
in_progress = Filter('stage', 'in_progress', '==', 'string')
price_range = Filter('price', 10, 'between', 'number')
price_range.valueF = 100
records = jestor.table('products').get(filters=[in_progress, price_range])An unknown operator is ignored, and the filter then matches every record. In the Operators class, only Operators.CONTAINS, Operators.DOES_NOT_CONTAIN and Operators.STARTS_WITH are recognized, so prefer the operator strings above.
Count Records
Use the count method with a list of the table name and, optionally, the filters.
filters = [
Filter('status', 'open', '==', 'string'),
]
total = jestor.count(['table_name', filters])
all_records = jestor.count(['table_name'])To count without filters, leave the filters out instead of passing an empty list.
Get Field Properties
Returns the options of a selection field (radio select, multiple select and tags): a list with the internal key and the label of each option. For other field types it returns an empty list.
options = jestor.table('table_name').getPropertiesFromField('status')
# [{'key': 'option_key', 'value': 'Option label'}, ...]Selection fields store the option key, not the label: use the keys to filter or save these fields.
Get Value From Field
Returns the label of an option key of a selection field, or None when the key doesn't exist.
label = jestor.table('table_name').getValueFromField('status', 'option_key')Create User
Use the user() method, then the createUser() method with a list of [email, password, profile_id, name]. It returns the user with its id_user, name, email and active.
user = jestor.user().createUser(['[email protected]', 'passworda@123', '1', 'Test'])The user is created with a builder seat. The super admin profile can't be assigned.
Inactivate User
Use the user() method, then the InactiveUser() method with a list with the user id.
jestor.user().InactiveUser([id_user])List Users
Use the user() method, then the get method. It returns a list of users. The get method accepts these parameters:
- filters: a list of Filter. Default: no filters.
- limit: int. Default: 100.
- page: int. Default: 1.
- sort: str. Default: "id_user desc".
users = jestor.user().get()
filters = [
Filter('name', 'test', 'like', 'string'),
]
users = jestor.user().get(filters=filters, sort='name asc')List Tasks
Use the fetchTasks method. It returns a list of tasks. Optionally, pass a list of [filters, limit, page].
tasks = jestor.fetchTasks()
filters = [
Filter('description', 'test', 'like', 'string'),
]
limit = 10
page = 1
tasks = jestor.fetchTasks([filters, limit, page])Files
Use the file method to manage the files of a file field. It takes the following parameters:
- table: str, the table name.
- record_id: int, the record id. Leave it out for a new record.
- field: str, the file field name. Leave it out for a new record.
The files object has these methods:
- add(file): adds a file. The file is a dictionary with a 'name' and one of:
- 'content' and 'contentType': the file content and its extension, e.g. 'pdf'.
- 'fileUrl': the URL to download the file from.
- 'localFile': a file name returned by createNewFile, createNewFileFromBase64 or generatePDF.
- update(file_id, {'name': 'new name'}): renames a file.
- delete(file_id): removes a file.
- toJson(): the files to save in the field.
The changes are only saved when you save toJson() in the field. A file that can't be added (e.g. an invalid URL) is skipped without an error.
Adding, renaming and removing files of an existing record:
table_name = 'table_name'
record_id = 1
field = 'file_field'
files = jestor.file(table_name, record_id, field)
files.add({'name': 'file_test', 'content': '<content string>', 'contentType': 'txt'})
files.update('E0DOdSKgvkkMncI8Fnhst-2', {'name': 'file_update_name'})
files.delete('A1CVwLAxzjjYprO5Bjdfi-5')
jestor.table(table_name).update(record_id, {field: files.toJson()})Adding files to a new record:
table_name = 'table_name'
files = jestor.file(table_name)
files.add({'name': 'file_test', 'fileUrl': 'https://example.com/file.pdf'})
jestor.table(table_name).insert({'name': 'create new record', 'files': files.toJson()})POST
Use the post method to send data to an external endpoint, with a list of [url, headers, body]. The headers are a list of "Name: value" strings, and a dictionary body is sent as JSON.
url = 'https://example.com/api/items'
headers = [
'Authorization: Bearer <token>',
]
body = {
'name': 'example',
}
result = jestor.post([url, headers, body])
status_code = result['info']['http_code']
content = result['content'] # the response body, as textYou can also import requests to call external endpoints.
GET
Use the get method to call an external endpoint, with a list of [url, headers]. It returns the same result as post.
url = 'https://example.com/api/items'
headers = [
'Accept: application/json',
]
result = jestor.get([url, headers])
content = result['content']stopCodeExecution()
In synchronous triggers, stopCodeExecution() stops the code, rolls back the save and shows the message to the user.
if currentData['stage'] == 'done' and currentData['amount'] == 0:
stopCodeExecution("You can't close deals with no $ amount!")showMessage()
In synchronous triggers and functions, showMessage() shows a message to the user after the run.
Parameters:
- message: str, required.
- type: Type.SUCCESS or Type.WARNING. Default: Type.SUCCESS.
showMessage('Record added successfully', Type.SUCCESS)Generate PDF
Creates a PDF from HTML, with a list of [html, page_size, orientation]. The page size defaults to "A4" and the orientation to "landscape". It returns the file name of the PDF, to add to a file field.
html = '''
<body>
<h2>Welcome to Jestor</h2>
<p>This PDF was generated from HTML in a low-code trigger.</p>
</body>
'''
pdf = jestor.generatePDF([html, 'A4', 'portrait'])
files = jestor.file('table_name')
files.add({'name': 'welcome', 'localFile': pdf})
jestor.table('table_name').update(afterSave['id_table_name'], {'attachments': files.toJson()})Create New File
Creates a file from a content and its extension. It returns the file name, which can be saved in a file field: it is added to the files the field already has.
new_file = jestor.createNewFile(['test file content', 'txt'])
jestor.table('table_name').update(recordData['id_table_name'], {'files': new_file})Create New File Base64
Creates a file from a base64 content and its extension. It returns the file name, like createNewFile.
new_file = jestor.createNewFileFromBase64(['dGVzdCBmaWxlIGNvbnRlbnQ=', 'txt'])
jestor.table('table_name').update(recordData['id_table_name'], {'files': new_file})Get Content File
Returns the content of a file saved in Jestor, in base64. Pass the file value of one of the files of a file field.
import base64
import json
field_value = currentData['pictures']
pictures = json.loads(field_value) if isinstance(field_value, str) else field_value
content_base64 = jestor.getContentFile([pictures[0]['file']])
content = base64.b64decode(content_base64)Download File
Downloads a file from a URL and returns its content in base64, or None when the URL is not an http(s) URL.
content_base64 = jestor.downloadFile(['https://example.com/file.jpg'])
new_file = jestor.createNewFileFromBase64([content_base64, 'jpg'])
jestor.table('table_name').update(recordData['id_table_name'], {'files': new_file})Generate QR Code
Creates a QR code image (PNG) from a text and adds it to a file field of a record.
jestor.table('table_name').basicQRCode(data='https://www.jestor.com', id=1, field='file_field')Generate Barcode
Creates a Code 128 barcode image (PNG) from a text and adds it to a file field of a record.
jestor.table('table_name').barCode(data='887877979879', id=1, field='file_field')Example of using Low-code (Python)
Updated 3 days ago
