Server Script Hooks

Server Scripts in Frappe are a way to execute custom Python code triggered by document events or specific actions on the server. Server Scripts complement hooks by allowing code to be written directly within the Frappe UI, without modifying Python files or requiring deployment.


Server Script Hooks

These are available types of server script hooks:

  1. API (Method)
    Define a custom endpoint accessible via REST APIs. Trigger: Executed when the defined method is called.
    # Example: API Server Script
    frappe.publish_realtime('show_notification', message="API Triggered!")
    

  1. Document Event
    Similar to document hooks in hooks.py, these scripts are triggered on document lifecycle events.
    Supported Triggers:
    • Before Insert
    • After Insert
    • Before Save
    • After Save
    • Before Submit
    • After Submit
    • Before Cancel
    • After Cancel
    • Before Delete
    • After Delete
      # Example: Before Save Script
      if doc.total < 0:
          frappe.throw("Total cannot be negative.")
      

  1. Scheduled Script (Cron Jobs)
    Run custom logic periodically based on a schedule defined using cron syntax.
    Trigger: Follows a specific schedule.

    Example:

    # Send daily summary email
    users = frappe.get_all("User", filters={"enabled": 1})
    for user in users:
        frappe.sendmail(recipients=user.email, subject="Daily Summary", message="Hello!")
    

  1. Permission Query
    Add custom filters to control data visibility dynamically.
    Trigger: Applied when fetching data for list views or reports.

    Example:

    # Restrict visibility of Sales Invoice to the logged-in user's territory
    if not user.has_role("Administrator"):
        conditions["territory"] = frappe.db.get_value("User", frappe.session.user, "territory")
    

  1. Custom Field Logic
    Apply custom validation or computation logic directly to specific fields.
    Trigger: Executed during field changes.

    Example:

    # Automatically calculate a discount based on total
    if doc.total > 5000:
        doc.discount_percentage = 10
    

Differences Between Hooks and Server Scripts

Feature Hooks (Python Code) Server Scripts (UI Code)
Deployment Requires file modification and restart No deployment; changes apply instantly
Customization Scope Comprehensive Limited to simple use cases
Best for Complex and large-scale customizations Quick tweaks or temporary changes

Both approaches can be used depending on the use case. Server Scripts are ideal for minor changes, while hooks.py is better suited for robust, reusable logic.

Discard
Save
Was this article helpful?

On this page