You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

45 lines
1.1 KiB

  1. import json
  2. import frappe
  3. from frappe.utils import cstr
  4. queue_prefix = 'insert_queue_for_'
  5. @frappe.whitelist()
  6. def deferred_insert(doctype, records):
  7. frappe.cache().rpush(queue_prefix + doctype, records)
  8. def save_to_db():
  9. queue_keys = frappe.cache().get_keys(queue_prefix)
  10. for key in queue_keys:
  11. record_count = 0
  12. queue_key = get_key_name(key)
  13. doctype = get_doctype_name(key)
  14. while frappe.cache().llen(queue_key) > 0 and record_count <= 500:
  15. records = frappe.cache().lpop(queue_key)
  16. records = json.loads(records.decode('utf-8'))
  17. if isinstance(records, dict):
  18. record_count += 1
  19. insert_record(records, doctype)
  20. continue
  21. for record in records:
  22. record_count += 1
  23. insert_record(record, doctype)
  24. frappe.db.commit()
  25. def insert_record(record, doctype):
  26. if not record.get('doctype'):
  27. record['doctype'] = doctype
  28. try:
  29. doc = frappe.get_doc(record)
  30. doc.insert()
  31. except Exception as e:
  32. print(e, doctype)
  33. def get_key_name(key):
  34. return cstr(key).split('|')[1]
  35. def get_doctype_name(key):
  36. return cstr(key).split(queue_prefix)[1]