」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何編寫客戶端腳本來刪除frappe中的doctype所有數據

如何編寫客戶端腳本來刪除frappe中的doctype所有數據

發佈於2024-11-08
瀏覽:690

how to write client script for delete doctype all data in frappe

这是一篇包含您提供的脚本的博客文章:


使用Frappe批量删除WhatsApp消息

管理任何系统中的大量数据都可能具有挑战性,特别是在有效删除记录时。在Frappe中,我们可以通过自定义列表视图并批量删除记录来处理这种情况,以避免服务器过载。

在这篇文章中,我们将探讨如何使用 Frappe 中的自定义代码设置批量删除“WhatsApp Message”文档。

为什么要批量删除?

当处理数千或更多记录时,尝试一次删除它们可能会给您的服务器带来压力,导致超时或性能下降。批处理使我们能够将任务分解为更小的、可管理的块,从而减少服务器上的负载并确保更流畅的用户体验。

自定义列表视图

首先,我们将修改“WhatsApp Message”文档类型的列表视图,添加用于批量删除的按钮。此按钮将触发批量删除所有WhatsApp消息的过程。

自定义列表视图的代码如下:

frappe.listview_settings['WhatsApp Message'] = {
    onload: function(listview) {
        // Add a custom button in the list view
        // Uncomment this section to enable the button
         listview.page.add_inner_button(__('Delete All Docs'), function() {
            // Confirm before proceeding with the deletion
             frappe.confirm(
                 'Are you sure you want to delete all Whatsapp messages?',
                 function() {
                     Start the batch deletion process
                     delete_in_batches();
                 }
             );
         });
    }
};

代码的注释部分向列表视图添加了一个标有“删除所有文档”的按钮。单击后,它会在开始删除过程之前提示用户确认。您可以取消注释这部分代码以在您的环境中启用该按钮。

批量删除功能

这个过程的核心是delete_in_batches函数。该函数获取一批文档,逐个删除它们,然后延迟处理下一批文档,确保服务器不会不堪重负。

批量删除完整代码如下:

function delete_in_batches(batch_size = 2000) {
    // Step 1: Fetch a batch of documents to be deleted
    frappe.call({
        method: "frappe.client.get_list",
        args: {
            doctype: "WhatsApp Message",  // Your target doctype
            fields: ["name"],  // Fetch only the 'name' field (docnames)
            limit: batch_size  // Process in batches of 2000
        },
        callback: function(response) {
            let docs = response.message;

            if (docs && docs.length > 0) {
                // Step 2: Loop through each document in the batch and delete it
                docs.forEach(function(doc, index) {
                    frappe.call({
                        method: "frappe.client.delete",
                        args: {
                            doctype: "WhatsApp Message",  // Ensure this is correct
                            name: doc.name
                        },
                        callback: function(r) {
                            if (!r.exc) {
                                frappe.show_alert({
                                    message: `Document ${doc.name} deleted`,
                                    indicator: 'green'
                                });
                            }
                        }
                    });
                });

                // Step 3: Delay the next batch to prevent server overload
                setTimeout(function() {
                    delete_in_batches(batch_size);  // Recursive call to delete the next batch
                }, 2000);  // 2-second delay between batches
            } else {
                // No more documents to delete
                frappe.msgprint("All WhatsApp messages have been deleted.");
                frappe.listview.refresh();  // Refresh the list view once the process completes
            }
        }
    });
}

运作原理:

  1. 获取文档:

    该函数首先获取一批 WhatsApp Message 文档,批次的大小由batch_size 参数控制(默认为 2000)。

  2. 删除文档:

    对于获取的每个文档,脚本都会调用 frappe.client.delete 方法来删​​除该文档。每次成功删除后,都会向用户显示一条通知。

  3. 递归批处理:

    处理完一个批次后,该函数会暂停 2 秒,然后再获取并删除下一个批次。此延迟有助于防止服务器过载。

  4. 完成:

    当没有更多文档要删除时,会向用户显示一条消息,并刷新列表视图以反映更改。

结论:

这个脚本是一个简单而有效的解决方案,用于批量删除Frappe中的大量数据。通过将删除过程分成更小的、可管理的批次,我们可以避免服务器过载并确保操作顺利运行。您可以根据数据量和服务器容量修改批量大小和延迟以满足您的需求。

请随意将此脚本集成到您自己的 Frappe 应用程序中,以简化 WhatsApp 消息或任何其他文档类型的删除。

编写客户端脚本后,将此逻辑写入服务器脚本中,选择服务器脚本类型 API 并将此代码写入脚本中

下面是代码的详细解释,包括代码本身:

import frappe

@frappe.whitelist()
def delete_all_docs(doctype):
    # Get all documents of the specified doctype
    docs = frappe.get_all(doctype)

    # Loop through each document in the list
    for doc in docs:
        # Delete the document using its name and the provided doctype
        frappe.delete_doc(doctype, doc.name, force=1)

    # Commit the changes to the database to make deletions permanent
    frappe.db.commit()

    # Return a confirmation message
    return f"All documents from {doctype} have been deleted."

代码细分:

  1. import frappe:导入 frappe 模块,它是 Frappe 框架的核心,允许您访问数据库和服务器功能。

  2. @frappe.whitelist():此装饰器允许通过 Frappe 的 API 访问函数 delete_all_docs,并可从外部应用程序或脚本调用。

  3. def delete_all_docs(doctype)::定义该函数接受一个参数:

    • doctype:将删除所有记录的文档类型(例如“员工”、“客户”)。
  4. docs = frappe.get_all(doctype):这会获取指定 doctype 的所有文档并将它们存储在 docs 变量中。返回的每个文档将包含文档名称,用于删除。

  5. for doc in docs::该函数循环遍历列表 docs 中的每个文档。

  6. frappe.delete_doc(doctype, doc.name, force=1):在循环内,通过指定 doctype 和 doc.name 删除每个文档。 force=1 参数确保文档被强制删除,绕过验证规则并在必要时进行检查。

  7. frappe.db.commit():删除所有文档后,将提交数据库更改,使删除永久化。

  8. return f"所有来自{doctype}的文档已被删除。":删除所有文档后,返回成功信息,表示操作成功。

当您需要从 Frappe 应用程序中的特定文档类型中删除所有文档时,此功能非常有用。

版本聲明 本文轉載於:https://dev.to/04anilr/how-to-write-client-script-for-delete-doctype-all-data-in-frappe-18e0?1如有侵犯,請聯絡study_golang@163 .com刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3