导入并解析文件以填写表单

Import and parse a file to fill the form

目前,我正在开发自定义应用程序。到目前为止,我已准备好手动填写 DocType。我们得到了文件(SQLite3),我想上传、解析、提取必要的字段并填写表格。基本上和导入数据工具一样。在我的例子中,不需要批量操作,如果可能的话,在服务器端进行提取部分。

到目前为止我尝试了什么

我添加了一个服务器操作来调用我的应用程序的白名单方法。我可以通过以下方式获取当前文档:

@frappe.whitelist()
def upload_data_and_extract(doc: str):
    """
        Uploads and processes an existing file and extracts data from it
    """
    doc_dict = json.loads(doc)
    custom_dt = frappe.get_doc('CustomDT', doc_dict['name'])
    # parse data here
    custom_dt.custom_field = "new value from parsed data"
    custom_dt.save()
    return doc # How do I return a JSON back to the website from the updated doc?

使用这种方法,我只能在文档保存之前进行解析。我宁愿在 attach 字段被修改时更新表单的字段。因此,我尝试了服务器端脚本方法:

frappe.ui.form.on('CustomDT', {
    original_data: function(frm, cdt, cdn) {
        if(original_data) {
            frappe.call({
                method: "customapp.customapp.doctype.customdt.customdt.parse_file",
                args: {
                    "doc": frm.doc
                },
                callback: function(r) {
                    // code snippet
                }
            });
        }
    }
});

这是我的问题:

  1. 上传需要解析以填写表单的文件的最佳方法是什么?
  2. 如何以最简单的方式访问上传的文件(附件)。 (有没有类似frappe.get_attachment()的东西?)
  3. 如何轻松地刷新 callback 中的表单字段?

感谢您对这些主题的任何帮助。

西蒙

我开发了相同的工具,但那是用于 CSV 上传的。我将分享它,以帮助您实现目标。

JS 文件。

// Copyright (c) 2020, Bhavesh and contributors
// For license information, please see license.txt

    frappe.ui.form.on('Car Upload Tool', {
        upload: function(frm) {
            frm.call({
                doc: frm.doc,
                method:"upload_data",
                freeze:true,
                freeze_message:"Data Uploading ...",
                callback:function(r){
                    console.log(r)
                }
            })
        }
    });

Python代码

# -*- coding: utf-8 -*-
# Copyright (c) 2020, Bhavesh and contributors
# For license information, please see license.txt

from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from carrental.carrental.doctype.car_upload_tool.csvtojson import csvtojson
import csv 
import json

class CarUploadTool(Document):
    def upload_data(self):
        _file = frappe.get_doc("File", {"file_url": self.attach_file})
        filename = _file.get_full_path()
        csv_json = csv_to_json(filename)
        make_car(csv_json)
        


def csv_to_json(csvFilePath):
    jsonArray = []
    #read csv file
    with open(csvFilePath, encoding='latin-1') as csvf:
        #load csv file data using csv library's dictionary reader
        csvReader = csv.DictReader(csvf,delimiter=";")

        #convert each csv row into python dict
        for row in csvReader:
            frappe.errprint(row)
            #add this python dict to json array
            jsonArray.append(row)  
    #convert python jsonArray to JSON String and write to file
    return jsonArray

def make_car(car_details):
    for row in car_details:
        create_brand(row.get('Marke'))
        create_car_type(row.get('Fahrzeugkategorie'))
        if not frappe.db.exists("Car",row.get('Fahrgestellnr.')):
            car_doc = frappe.get_doc(dict(
                doctype = "Car",
                brand = row.get('Marke'),
                model_and_description = row.get('Bezeichnung'),
                type_of_fuel = row.get('Motorart'),
                color = row.get('Farbe'),
                transmission = row.get('Getriebeart'),
                horsepower = row.get('Leistung (PS)'),
                car_type = row.get('Fahrzeugkategorie'),
                car_vin_id = row.get('Fahrgestellnr.'),
                licence_plate = row.get('Kennzeichen'),
                location_code = row.get('Standort')
            ))
            car_doc.model = car_doc.model_and_description.split(' ')[0] or ''
            car_doc.insert(ignore_permissions = True)
        else:
            car_doc = frappe.get_doc("Car",row.get('Fahrgestellnr.'))
            car_doc.brand = row.get('Marke')
            car_doc.model_and_description = row.get('Bezeichnung')
            car_doc.model = car_doc.model_and_description.split(' ')[0] or ''
            car_doc.type_of_fuel = row.get('Motorart')
            car_doc.color = row.get('Farbe')
            car_doc.transmission = row.get('Getriebeart')
            car_doc.horsepower = row.get('Leistung (PS)')
            car_doc.car_type = row.get('Fahrzeugkategorie')
            car_doc.car_vin_id = row.get('Fahrgestellnr.')
            car_doc.licence_plate = row.get('Kennzeichen')
            car_doc.location_code = row.get('Standort')
            car_doc.save(ignore_permissions = True)
    frappe.msgprint("Car Uploaded Successfully")


def create_brand(brand):
    if not frappe.db.exists("Brand",brand):
        frappe.get_doc(dict(
            doctype = "Brand",
            brand = brand
        )).insert(ignore_permissions = True)

def create_car_type(car_type):
    if not frappe.db.exists("Vehicle Type",car_type):
        frappe.get_doc(dict(
            doctype = "Vehicle Type",
            vehicle_type = car_type
        )).insert(ignore_permissions = True)

因此,对于这个上传工具,我创建了一个包含以下字段的文档类型:

  1. 附加文件(字段类型 = 附加)
  2. 按钮(字段类型 = 按钮)