您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

159 行
4.9 KiB

  1. # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
  2. # MIT License. See license.txt
  3. from __future__ import unicode_literals
  4. import webnotes
  5. from webnotes import msgprint, _
  6. import json
  7. import csv, cStringIO
  8. from webnotes.utils import encode, cstr, cint, flt
  9. def read_csv_content_from_uploaded_file(ignore_encoding=False):
  10. if getattr(webnotes, "uploaded_file", None):
  11. with open(webnotes.uploaded_file, "r") as upfile:
  12. fcontent = upfile.read()
  13. else:
  14. from webnotes.utils.file_manager import get_uploaded_content
  15. fname, fcontent = get_uploaded_content()
  16. return read_csv_content(fcontent, ignore_encoding)
  17. def read_csv_content_from_attached_file(doc):
  18. fileid = webnotes.conn.get_value("File Data", {"attached_to_doctype": doc.doctype,
  19. "attached_to_name":doc.name}, "name")
  20. if not fileid:
  21. msgprint("File not attached!")
  22. raise Exception
  23. try:
  24. from webnotes.utils.file_manager import get_file
  25. fname, fcontent = get_file(fileid)
  26. return read_csv_content(fcontent, webnotes.form_dict.get('ignore_encoding_errors'))
  27. except Exception, e:
  28. webnotes.msgprint("""Unable to open attached file. Please try again.""")
  29. raise Exception
  30. def read_csv_content(fcontent, ignore_encoding=False):
  31. rows = []
  32. try:
  33. reader = csv.reader(fcontent.splitlines())
  34. # decode everything
  35. csvrows = [[val for val in row] for row in reader]
  36. for row in csvrows:
  37. newrow = []
  38. for val in row:
  39. if ignore_encoding:
  40. newrow.append(cstr(val.strip()))
  41. else:
  42. try:
  43. newrow.append(unicode(val.strip(), 'utf-8'))
  44. except UnicodeDecodeError, e:
  45. webnotes.msgprint("""Some character(s) in row #%s, column #%s are
  46. not readable by utf-8. Ignoring them. If you are importing a non
  47. english language, please make sure your file is saved in the 'utf-8'
  48. encoding.""" % (csvrows.index(row)+1, row.index(val)+1))
  49. raise Exception
  50. rows.append(newrow)
  51. return rows
  52. except Exception, e:
  53. webnotes.msgprint("Not a valid Comma Separated Value (CSV File)")
  54. raise e
  55. @webnotes.whitelist()
  56. def send_csv_to_client(args):
  57. if isinstance(args, basestring):
  58. args = json.loads(args)
  59. args = webnotes._dict(args)
  60. webnotes.response["result"] = cstr(to_csv(args.data))
  61. webnotes.response["doctype"] = args.filename
  62. webnotes.response["type"] = "csv"
  63. def to_csv(data):
  64. writer = UnicodeWriter()
  65. for row in data:
  66. writer.writerow(row)
  67. return writer.getvalue()
  68. class UnicodeWriter:
  69. def __init__(self, encoding="utf-8"):
  70. self.encoding = encoding
  71. self.queue = cStringIO.StringIO()
  72. self.writer = csv.writer(self.queue, quoting=csv.QUOTE_NONNUMERIC)
  73. def writerow(self, row):
  74. row = encode(row, self.encoding)
  75. self.writer.writerow(row)
  76. def getvalue(self):
  77. return self.queue.getvalue()
  78. def check_record(d, parenttype=None, doctype_dl=None):
  79. """check for mandatory, select options, dates. these should ideally be in doclist"""
  80. from webnotes.utils.dateutils import parse_date
  81. if parenttype and not d.get('parent'):
  82. webnotes.msgprint(_("Parent is required."), raise_exception=1)
  83. if not doctype_dl:
  84. doctype_dl = webnotes.model.doctype.get(d.doctype)
  85. for key in d:
  86. docfield = doctype_dl.get_field(key)
  87. val = d[key]
  88. if docfield:
  89. if docfield.reqd and (val=='' or val==None):
  90. webnotes.msgprint("%s is mandatory." % docfield.label, raise_exception=1)
  91. if docfield.fieldtype=='Select' and val and docfield.options:
  92. if docfield.options.startswith('link:'):
  93. link_doctype = docfield.options.split(':')[1]
  94. if not webnotes.conn.exists(link_doctype, val):
  95. webnotes.msgprint("%s: %s must be a valid %s" % (docfield.label, val, link_doctype),
  96. raise_exception=1)
  97. elif docfield.options == "attach_files:":
  98. pass
  99. elif val not in docfield.options.split('\n'):
  100. webnotes.msgprint("%s must be one of: %s" % (docfield.label,
  101. ", ".join(filter(None, docfield.options.split("\n")))), raise_exception=1)
  102. if val and docfield.fieldtype=='Date':
  103. d[key] = parse_date(val)
  104. elif val and docfield.fieldtype in ["Int", "Check"]:
  105. d[key] = cint(val)
  106. elif val and docfield.fieldtype in ["Currency", "Float"]:
  107. d[key] = flt(val)
  108. def import_doc(d, doctype, overwrite, row_idx, submit=False):
  109. """import main (non child) document"""
  110. if d.get("name") and webnotes.conn.exists(doctype, d['name']):
  111. if overwrite:
  112. bean = webnotes.bean(doctype, d['name'])
  113. bean.doc.fields.update(d)
  114. if d.get("docstatus") == 1:
  115. bean.update_after_submit()
  116. else:
  117. bean.save()
  118. return 'Updated row (#%d) %s' % (row_idx + 1, getlink(doctype, d['name']))
  119. else:
  120. return 'Ignored row (#%d) %s (exists)' % (row_idx + 1,
  121. getlink(doctype, d['name']))
  122. else:
  123. bean = webnotes.bean([d])
  124. bean.insert()
  125. if submit:
  126. bean.submit()
  127. return 'Inserted row (#%d) %s' % (row_idx + 1, getlink(doctype,
  128. bean.doc.fields['name']))
  129. def getlink(doctype, name):
  130. return '<a href="#Form/%(doctype)s/%(name)s">%(name)s</a>' % locals()