Data Script

The Data Script feature is essential for retrieving, processing, and delivering dynamic data to your web pages from various sources. This write-up will help you with how to effectively utilize Data Script to ensure your content is always current and relevant.

Key Concepts

Data Binding

To display data on your page, you need to assign the data to a data variable. This variable is used to pass data to the web page.

data.events = ...  # Example of assigning data to the 'events' variable
data.user_list = ...  # Example of assigning data to the 'user\_list' variable

Note:

  • Data scripts must be written in Python and are executed server-side.
  • They are executed in a restricted Python environment and can only access whitelisted modules. You can find the list of whitelisted methods here.

Retrieving Data from Frappe DocType

You can use Data Scripts to fetch both lists of documents and single document from your Frappe DocType.

Fetching a Document List

To retrieve all records of a specific DocType:

data.users = frappe.get_all("User")

To retrieve a filtered subset of documents (e.g., active users):

data.active_users = frappe.get_all("User", filters={"enabled": 1})

Fetching a Single Document

To retrieve a single document by its name or another identifier:

data.user = frappe.get_doc("User", "<user-email>")

Fetching Data from External Resources

Data Scripts can also fetch data from external APIs or resources, allowing for the integration of third-party data into your page.

data.posts = frappe.make_get_request("https://jsonplaceholder.typicode.com/posts")

Processing Data

To process data retrieved from Frappe DocType or external resources, you can use Python code within your Data Script.

data.users = frappe.get_list("User")

# processing data
for user in data.users:
    user.full_name = user.first_name + " " + user.last_name

# Adding routes to each user
for user in data.users:
    user.route = "/user/" + user.name

Passing Data to Client-Side

If you want to pass data to the client-side, you can set the value to the data.page_data variable. It should be a dictionary. Once you set the value to data.page_data, it will be available on the client-side as window.page_data.

data.page_data = {
    "enabled\_languages": ["English", "Spanish", "French"]
    ...
}

With this, client-side should have following data.Screenshot 2024-08-26 at 3.59.34 PM

Discard
Save

On this page