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.
 
 
 
 
 
 

865 lines
22 KiB

  1. # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
  2. # MIT License. See license.txt
  3. # util __init__.py
  4. from __future__ import unicode_literals
  5. import webnotes
  6. user_time_zone = None
  7. user_format = None
  8. current_date = None
  9. no_value_fields = ['Section Break', 'Column Break', 'HTML', 'Table', 'FlexTable',
  10. 'Button', 'Image', 'Graph']
  11. default_fields = ['doctype', 'name', 'owner', 'creation', 'modified', 'modified_by',
  12. 'parent', 'parentfield', 'parenttype', 'idx', 'docstatus']
  13. # used in import_docs.py
  14. # TODO: deprecate it
  15. def getCSVelement(v):
  16. """
  17. Returns the CSV value of `v`, For example:
  18. * apple becomes "apple"
  19. * hi"there becomes "hi""there"
  20. """
  21. v = cstr(v)
  22. if not v: return ''
  23. if (',' in v) or ('\n' in v) or ('"' in v):
  24. if '"' in v: v = v.replace('"', '""')
  25. return '"'+v+'"'
  26. else: return v or ''
  27. def get_fullname(profile):
  28. """get the full name (first name + last name) of the user from Profile"""
  29. p = webnotes.conn.sql("""select first_name, last_name from `tabProfile`
  30. where name=%s""", profile, as_dict=1)
  31. if p:
  32. profile = " ".join(filter(None,
  33. [p[0].get('first_name'), p[0].get('last_name')])) or profile
  34. return profile
  35. def get_formatted_email(user):
  36. """get email id of user formatted as: John Doe <johndoe@example.com>"""
  37. if user == "Administrator":
  38. return user
  39. from email.utils import formataddr
  40. fullname = get_fullname(user)
  41. return formataddr((fullname, user))
  42. def extract_email_id(email):
  43. """fetch only the email part of the email id"""
  44. from email.utils import parseaddr
  45. if ',' in email and email.count("@")==1:
  46. email = email.split(",")[-1]
  47. fullname, email_id = parseaddr(email)
  48. if isinstance(email_id, basestring) and not isinstance(email_id, unicode):
  49. email_id = email_id.decode("utf-8", "ignore")
  50. return email_id
  51. def validate_email_add(email_str):
  52. """Validates the email string"""
  53. email = extract_email_id(email_str)
  54. import re
  55. return re.match("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", email.lower())
  56. def get_request_site_address(full_address=False):
  57. """get app url from request"""
  58. import os, conf
  59. if hasattr(conf, "host_name"):
  60. host_name = conf.host_name
  61. else:
  62. try:
  63. protocol = 'HTTPS' in os.environ.get('SERVER_PROTOCOL') and 'https://' or 'http://'
  64. host_name = protocol + os.environ.get('HTTP_HOST')
  65. except TypeError:
  66. return 'http://localhost'
  67. if full_address:
  68. return host_name + os.environ.get("REQUEST_URI", "")
  69. else:
  70. return host_name
  71. def random_string(length):
  72. """generate a random string"""
  73. import string
  74. from random import choice
  75. return ''.join([choice(string.letters + string.digits) for i in range(length)])
  76. def load_json(arg):
  77. # already a dictionary?
  78. if not isinstance(arg, basestring):
  79. return arg
  80. import json
  81. return json.loads(arg, encoding='utf-8')
  82. # Get Traceback
  83. # ==============================================================================
  84. def getTraceback():
  85. """
  86. Returns the traceback of the Exception
  87. """
  88. import sys, traceback
  89. exc_type, value, tb = sys.exc_info()
  90. trace_list = traceback.format_tb(tb, None) + \
  91. traceback.format_exception_only(exc_type, value)
  92. body = "Traceback (innermost last):\n" + "%-20s %s" % \
  93. (unicode((b"").join(trace_list[:-1]), 'utf-8'), unicode(trace_list[-1], 'utf-8'))
  94. if webnotes.logger:
  95. webnotes.logger.error('Db:'+(webnotes.conn and webnotes.conn.cur_db_name or '') \
  96. + ' - ' + body)
  97. return body
  98. def log(event, details):
  99. webnotes.logger.info(details)
  100. # datetime functions
  101. def getdate(string_date):
  102. """
  103. Coverts string date (yyyy-mm-dd) to datetime.date object
  104. """
  105. import datetime
  106. if isinstance(string_date, datetime.date):
  107. return string_date
  108. elif isinstance(string_date, datetime.datetime):
  109. return datetime.date()
  110. if " " in string_date:
  111. string_date = string_date.split(" ")[0]
  112. return datetime.datetime.strptime(string_date, "%Y-%m-%d").date()
  113. def add_to_date(date, years=0, months=0, days=0):
  114. """Adds `days` to the given date"""
  115. format = isinstance(date, basestring)
  116. if date:
  117. date = getdate(date)
  118. else:
  119. raise Exception, "Start date required"
  120. from dateutil.relativedelta import relativedelta
  121. date += relativedelta(years=years, months=months, days=days)
  122. if format:
  123. return date.strftime("%Y-%m-%d")
  124. else:
  125. return date
  126. def add_days(date, days):
  127. return add_to_date(date, days=days)
  128. def add_months(date, months):
  129. return add_to_date(date, months=months)
  130. def add_years(date, years):
  131. return add_to_date(date, years=years)
  132. def date_diff(string_ed_date, string_st_date):
  133. return (getdate(string_ed_date) - getdate(string_st_date)).days
  134. def time_diff(string_ed_date, string_st_date):
  135. return get_datetime(string_ed_date) - get_datetime(string_st_date)
  136. def time_diff_in_seconds(string_ed_date, string_st_date):
  137. return time_diff(string_ed_date, string_st_date).seconds
  138. def time_diff_in_hours(string_ed_date, string_st_date):
  139. return round(float(time_diff(string_ed_date, string_st_date).seconds) / 3600, 6)
  140. def now_datetime():
  141. from datetime import datetime
  142. return convert_utc_to_user_timezone(datetime.utcnow())
  143. def get_user_time_zone():
  144. global user_time_zone
  145. if not user_time_zone:
  146. user_time_zone = webnotes.cache().get_value("time_zone")
  147. if not user_time_zone:
  148. user_time_zone = webnotes.conn.get_value('Control Panel', None, 'time_zone') \
  149. or 'Asia/Calcutta'
  150. webnotes.cache().set_value("time_zone", user_time_zone)
  151. return user_time_zone
  152. def convert_utc_to_user_timezone(utc_timestamp):
  153. from pytz import timezone
  154. utcnow = timezone('UTC').localize(utc_timestamp)
  155. return utcnow.astimezone(timezone(get_user_time_zone()))
  156. def now():
  157. """return current datetime as yyyy-mm-dd hh:mm:ss"""
  158. if current_date:
  159. return getdate(current_date).strftime("%Y-%m-%d") + " " + now_datetime().strftime('%H:%M:%S')
  160. else:
  161. return now_datetime().strftime('%Y-%m-%d %H:%M:%S')
  162. def nowdate():
  163. """return current date as yyyy-mm-dd"""
  164. return now_datetime().strftime('%Y-%m-%d')
  165. def today():
  166. return nowdate()
  167. def nowtime():
  168. """return current time in hh:mm"""
  169. return now_datetime().strftime('%H:%M')
  170. def get_first_day(dt, d_years=0, d_months=0):
  171. """
  172. Returns the first day of the month for the date specified by date object
  173. Also adds `d_years` and `d_months` if specified
  174. """
  175. import datetime
  176. dt = getdate(dt)
  177. # d_years, d_months are "deltas" to apply to dt
  178. overflow_years, month = divmod(dt.month + d_months - 1, 12)
  179. year = dt.year + d_years + overflow_years
  180. return datetime.date(year, month + 1, 1)
  181. def get_last_day(dt):
  182. """
  183. Returns last day of the month using:
  184. `get_first_day(dt, 0, 1) + datetime.timedelta(-1)`
  185. """
  186. import datetime
  187. return get_first_day(dt, 0, 1) + datetime.timedelta(-1)
  188. def get_datetime(datetime_str):
  189. from datetime import datetime
  190. if isinstance(datetime_str, datetime):
  191. return datetime_str.replace(microsecond=0, tzinfo=None)
  192. return datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S')
  193. def get_datetime_str(datetime_obj):
  194. if isinstance(datetime_obj, basestring):
  195. datetime_obj = get_datetime(datetime_obj)
  196. return datetime_obj.strftime('%Y-%m-%d %H:%M:%S')
  197. def formatdate(string_date=None):
  198. """
  199. Convers the given string date to :data:`user_format`
  200. User format specified in :term:`Control Panel`
  201. Examples:
  202. * dd-mm-yyyy
  203. * mm-dd-yyyy
  204. * dd/mm/yyyy
  205. """
  206. if string_date:
  207. string_date = getdate(string_date)
  208. else:
  209. string_date = now_datetime().date()
  210. global user_format
  211. if not user_format:
  212. user_format = webnotes.conn.get_default("date_format")
  213. out = user_format
  214. return out.replace("dd", string_date.strftime("%d"))\
  215. .replace("mm", string_date.strftime("%m"))\
  216. .replace("yyyy", string_date.strftime("%Y"))
  217. def global_date_format(date):
  218. """returns date as 1 January 2012"""
  219. formatted_date = getdate(date).strftime("%d %B %Y")
  220. return formatted_date.startswith("0") and formatted_date[1:] or formatted_date
  221. def dict_to_str(args, sep='&'):
  222. """
  223. Converts a dictionary to URL
  224. """
  225. import urllib
  226. t = []
  227. for k in args.keys():
  228. t.append(str(k)+'='+urllib.quote(str(args[k] or '')))
  229. return sep.join(t)
  230. def timestamps_equal(t1, t2):
  231. """Returns true if same the two string timestamps are same"""
  232. scrub = lambda x: x.replace(':', ' ').replace('-',' ').split()
  233. t1, t2 = scrub(t1), scrub(t2)
  234. if len(t1) != len(t2):
  235. return
  236. for i in range(len(t1)):
  237. if t1[i]!=t2[i]:
  238. return
  239. return 1
  240. def has_common(l1, l2):
  241. """Returns truthy value if there are common elements in lists l1 and l2"""
  242. return set(l1) & set(l2)
  243. def flt(s, precision=None):
  244. """Convert to float (ignore commas)"""
  245. if isinstance(s, basestring):
  246. s = s.replace(',','')
  247. try:
  248. num = float(s)
  249. if precision is not None:
  250. num = _round(num, precision)
  251. except Exception:
  252. num = 0
  253. return num
  254. def cint(s):
  255. """Convert to integer"""
  256. try: num = int(float(s))
  257. except: num = 0
  258. return num
  259. def cstr(s):
  260. if isinstance(s, unicode):
  261. return s
  262. elif s==None:
  263. return ''
  264. elif isinstance(s, basestring):
  265. return unicode(s, 'utf-8')
  266. else:
  267. return unicode(s)
  268. def _round(num, precision=0):
  269. """round method for round halfs to nearest even algorithm"""
  270. precision = cint(precision)
  271. multiplier = 10 ** precision
  272. # avoid rounding errors
  273. num = round(num * multiplier if precision else num, 8)
  274. import math
  275. floor = math.floor(num)
  276. decimal_part = num - floor
  277. if decimal_part == 0.5:
  278. num = floor if (floor % 2 == 0) else floor + 1
  279. else:
  280. num = round(num)
  281. return (num / multiplier) if precision else num
  282. def encode(obj, encoding="utf-8"):
  283. if isinstance(obj, list):
  284. out = []
  285. for o in obj:
  286. if isinstance(o, unicode):
  287. out.append(o.encode(encoding))
  288. else:
  289. out.append(o)
  290. return out
  291. elif isinstance(obj, unicode):
  292. return obj.encode(encoding)
  293. else:
  294. return obj
  295. def parse_val(v):
  296. """Converts to simple datatypes from SQL query results"""
  297. import datetime
  298. if isinstance(v, (datetime.date, datetime.datetime)):
  299. v = unicode(v)
  300. elif isinstance(v, datetime.timedelta):
  301. v = ":".join(unicode(v).split(":")[:2])
  302. elif isinstance(v, long):
  303. v = int(v)
  304. return v
  305. def fmt_money(amount, precision=None, currency=None):
  306. """
  307. Convert to string with commas for thousands, millions etc
  308. """
  309. number_format = webnotes.conn.get_default("number_format") or "#,###.##"
  310. decimal_str, comma_str, precision = get_number_format_info(number_format)
  311. amount = '%.*f' % (precision, flt(amount))
  312. if amount.find('.') == -1:
  313. decimals = ''
  314. else:
  315. decimals = amount.split('.')[1]
  316. parts = []
  317. minus = ''
  318. if flt(amount) < 0:
  319. minus = '-'
  320. amount = cstr(abs(flt(amount))).split('.')[0]
  321. if len(amount) > 3:
  322. parts.append(amount[-3:])
  323. amount = amount[:-3]
  324. val = number_format=="#,##,###.##" and 2 or 3
  325. while len(amount) > val:
  326. parts.append(amount[-val:])
  327. amount = amount[:-val]
  328. parts.append(amount)
  329. parts.reverse()
  330. amount = comma_str.join(parts) + (precision and (decimal_str + decimals) or "")
  331. amount = minus + amount
  332. if currency:
  333. symbol = webnotes.conn.get_value("Currency", currency, "symbol")
  334. if symbol:
  335. amount = symbol + " " + amount
  336. return amount
  337. number_format_info = {
  338. "#.###": ("", ".", 0),
  339. "#,###": ("", ",", 0),
  340. "#,###.##": (".", ",", 2),
  341. "#,##,###.##": (".", ",", 2),
  342. "#.###,##": (",", ".", 2),
  343. "# ###.##": (".", " ", 2),
  344. "#,###.###": (".", ",", 3),
  345. }
  346. def get_number_format_info(format):
  347. return number_format_info.get(format) or (".", ",", 2)
  348. #
  349. # convet currency to words
  350. #
  351. def money_in_words(number, main_currency = None, fraction_currency=None):
  352. """
  353. Returns string in words with currency and fraction currency.
  354. """
  355. d = get_defaults()
  356. if not main_currency:
  357. main_currency = d.get('currency', 'INR')
  358. if not fraction_currency:
  359. fraction_currency = webnotes.conn.get_value("Currency", main_currency, "fraction") or "Cent"
  360. n = "%.2f" % flt(number)
  361. main, fraction = n.split('.')
  362. if len(fraction)==1: fraction += '0'
  363. number_format = webnotes.conn.get_value("Currency", main_currency, "number_format") or \
  364. webnotes.conn.get_default("number_format") or "#,###.##"
  365. in_million = True
  366. if number_format == "#,##,###.##": in_million = False
  367. out = main_currency + ' ' + in_words(main, in_million).title()
  368. if cint(fraction):
  369. out = out + ' and ' + in_words(fraction, in_million).title() + ' ' + fraction_currency
  370. return out + ' only.'
  371. #
  372. # convert number to words
  373. #
  374. def in_words(integer, in_million=True):
  375. """
  376. Returns string in words for the given integer.
  377. """
  378. n=int(integer)
  379. known = {0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten',
  380. 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen',
  381. 19: 'nineteen', 20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fifty', 60: 'sixty', 70: 'seventy', 80: 'eighty', 90: 'ninety'}
  382. def psn(n, known, xpsn):
  383. import sys;
  384. if n in known: return known[n]
  385. bestguess, remainder = str(n), 0
  386. if n<=20:
  387. webnotes.errprint(sys.stderr)
  388. webnotes.errprint(n)
  389. webnotes.errprint("How did this happen?")
  390. assert 0
  391. elif n < 100:
  392. bestguess= xpsn((n//10)*10, known, xpsn) + '-' + xpsn(n%10, known, xpsn)
  393. return bestguess
  394. elif n < 1000:
  395. bestguess= xpsn(n//100, known, xpsn) + ' ' + 'hundred'
  396. remainder = n%100
  397. else:
  398. if in_million:
  399. if n < 1000000:
  400. bestguess= xpsn(n//1000, known, xpsn) + ' ' + 'thousand'
  401. remainder = n%1000
  402. elif n < 1000000000:
  403. bestguess= xpsn(n//1000000, known, xpsn) + ' ' + 'million'
  404. remainder = n%1000000
  405. else:
  406. bestguess= xpsn(n//1000000000, known, xpsn) + ' ' + 'billion'
  407. remainder = n%1000000000
  408. else:
  409. if n < 100000:
  410. bestguess= xpsn(n//1000, known, xpsn) + ' ' + 'thousand'
  411. remainder = n%1000
  412. elif n < 10000000:
  413. bestguess= xpsn(n//100000, known, xpsn) + ' ' + 'lakh'
  414. remainder = n%100000
  415. else:
  416. bestguess= xpsn(n//10000000, known, xpsn) + ' ' + 'crore'
  417. remainder = n%10000000
  418. if remainder:
  419. if remainder >= 100:
  420. comma = ','
  421. else:
  422. comma = ''
  423. return bestguess + comma + ' ' + xpsn(remainder, known, xpsn)
  424. else:
  425. return bestguess
  426. return psn(n, known, psn)
  427. # Get Defaults
  428. # ==============================================================================
  429. def get_defaults(key=None):
  430. """
  431. Get dictionary of default values from the :term:`Control Panel`, or a value if key is passed
  432. """
  433. return webnotes.conn.get_defaults(key)
  434. def set_default(key, val):
  435. """
  436. Set / add a default value to :term:`Control Panel`
  437. """
  438. return webnotes.conn.set_default(key, val)
  439. def remove_blanks(d):
  440. """
  441. Returns d with empty ('' or None) values stripped
  442. """
  443. empty_keys = []
  444. for key in d:
  445. if d[key]=='' or d[key]==None:
  446. # del d[key] raises runtime exception, using a workaround
  447. empty_keys.append(key)
  448. for key in empty_keys:
  449. del d[key]
  450. return d
  451. def pprint_dict(d, level=1, no_blanks=True):
  452. """
  453. Pretty print a dictionary with indents
  454. """
  455. if no_blanks:
  456. remove_blanks(d)
  457. # make indent
  458. indent, ret = '', ''
  459. for i in range(0,level): indent += '\t'
  460. # add lines
  461. comment, lines = '', []
  462. kl = d.keys()
  463. kl.sort()
  464. # make lines
  465. for key in kl:
  466. if key != '##comment':
  467. tmp = {key: d[key]}
  468. lines.append(indent + str(tmp)[1:-1] )
  469. # add comment string
  470. if '##comment' in kl:
  471. ret = ('\n' + indent) + '# ' + d['##comment'] + '\n'
  472. # open
  473. ret += indent + '{\n'
  474. # lines
  475. ret += indent + ',\n\t'.join(lines)
  476. # close
  477. ret += '\n' + indent + '}'
  478. return ret
  479. def get_common(d1,d2):
  480. """
  481. returns (list of keys) the common part of two dicts
  482. """
  483. return [p for p in d1 if p in d2 and d1[p]==d2[p]]
  484. def get_common_dict(d1, d2):
  485. """
  486. return common dictionary of d1 and d2
  487. """
  488. ret = {}
  489. for key in d1:
  490. if key in d2 and d2[key]==d1[key]:
  491. ret[key] = d1[key]
  492. return ret
  493. def get_diff_dict(d1, d2):
  494. """
  495. return common dictionary of d1 and d2
  496. """
  497. diff_keys = set(d2.keys()).difference(set(d1.keys()))
  498. ret = {}
  499. for d in diff_keys: ret[d] = d2[d]
  500. return ret
  501. def get_file_timestamp(fn):
  502. """
  503. Returns timestamp of the given file
  504. """
  505. import os
  506. from webnotes.utils import cint
  507. try:
  508. return str(cint(os.stat(fn).st_mtime))
  509. except OSError, e:
  510. if e.args[0]!=2:
  511. raise e
  512. else:
  513. return None
  514. # to be deprecated
  515. def make_esc(esc_chars):
  516. """
  517. Function generator for Escaping special characters
  518. """
  519. return lambda s: ''.join(['\\' + c if c in esc_chars else c for c in s])
  520. # esc / unescape characters -- used for command line
  521. def esc(s, esc_chars):
  522. """
  523. Escape special characters
  524. """
  525. if not s:
  526. return ""
  527. for c in esc_chars:
  528. esc_str = '\\' + c
  529. s = s.replace(c, esc_str)
  530. return s
  531. def unesc(s, esc_chars):
  532. """
  533. UnEscape special characters
  534. """
  535. for c in esc_chars:
  536. esc_str = '\\' + c
  537. s = s.replace(esc_str, c)
  538. return s
  539. def strip_html(text):
  540. """
  541. removes anything enclosed in and including <>
  542. """
  543. import re
  544. return re.compile(r'<.*?>').sub('', text)
  545. def escape_html(text):
  546. html_escape_table = {
  547. "&": "&amp;",
  548. '"': "&quot;",
  549. "'": "&apos;",
  550. ">": "&gt;",
  551. "<": "&lt;",
  552. }
  553. return "".join(html_escape_table.get(c,c) for c in text)
  554. def get_doctype_label(dt=None):
  555. """
  556. Gets label of a doctype
  557. """
  558. if dt:
  559. res = webnotes.conn.sql("""\
  560. SELECT name, dt_label FROM `tabDocType Label`
  561. WHERE name=%s""", dt)
  562. return res and res[0][0] or dt
  563. else:
  564. res = webnotes.conn.sql("SELECT name, dt_label FROM `tabDocType Label`")
  565. dt_label_dict = {}
  566. for r in res:
  567. dt_label_dict[r[0]] = r[1]
  568. return dt_label_dict
  569. def get_label_doctype(label):
  570. """
  571. Gets doctype from its label
  572. """
  573. res = webnotes.conn.sql("""\
  574. SELECT name FROM `tabDocType Label`
  575. WHERE dt_label=%s""", label)
  576. return res and res[0][0] or label
  577. def pretty_date(iso_datetime):
  578. """
  579. Takes an ISO time and returns a string representing how
  580. long ago the date represents.
  581. Ported from PrettyDate by John Resig
  582. """
  583. if not iso_datetime: return ''
  584. from datetime import datetime
  585. import math
  586. if isinstance(iso_datetime, basestring):
  587. iso_datetime = datetime.strptime(iso_datetime, '%Y-%m-%d %H:%M:%S')
  588. now_dt = datetime.strptime(now(), '%Y-%m-%d %H:%M:%S')
  589. dt_diff = now_dt - iso_datetime
  590. # available only in python 2.7+
  591. # dt_diff_seconds = dt_diff.total_seconds()
  592. dt_diff_seconds = dt_diff.days * 86400.0 + dt_diff.seconds
  593. dt_diff_days = math.floor(dt_diff_seconds / 86400.0)
  594. # differnt cases
  595. if dt_diff_seconds < 60.0:
  596. return 'just now'
  597. elif dt_diff_seconds < 120.0:
  598. return '1 minute ago'
  599. elif dt_diff_seconds < 3600.0:
  600. return '%s minutes ago' % cint(math.floor(dt_diff_seconds / 60.0))
  601. elif dt_diff_seconds < 7200.0:
  602. return '1 hour ago'
  603. elif dt_diff_seconds < 86400.0:
  604. return '%s hours ago' % cint(math.floor(dt_diff_seconds / 3600.0))
  605. elif dt_diff_days == 1.0:
  606. return 'Yesterday'
  607. elif dt_diff_days < 7.0:
  608. return '%s days ago' % cint(dt_diff_days)
  609. elif dt_diff_days < 31.0:
  610. return '%s week(s) ago' % cint(math.ceil(dt_diff_days / 7.0))
  611. elif dt_diff_days < 365.0:
  612. return '%s months ago' % cint(math.ceil(dt_diff_days / 30.0))
  613. else:
  614. return 'more than %s year(s) ago' % cint(math.floor(dt_diff_days / 365.0))
  615. def execute_in_shell(cmd, verbose=0):
  616. # using Popen instead of os.system - as recommended by python docs
  617. from subprocess import Popen
  618. import tempfile
  619. with tempfile.TemporaryFile() as stdout:
  620. with tempfile.TemporaryFile() as stderr:
  621. p = Popen(cmd, shell=True, stdout=stdout, stderr=stderr)
  622. p.wait()
  623. stdout.seek(0)
  624. out = stdout.read()
  625. stderr.seek(0)
  626. err = stderr.read()
  627. if verbose:
  628. if err: print err
  629. if out: print out
  630. return err, out
  631. def comma_or(some_list):
  632. return comma_sep(some_list, " or ")
  633. def comma_and(some_list):
  634. return comma_sep(some_list, " and ")
  635. def comma_sep(some_list, sep):
  636. if isinstance(some_list, (list, tuple)):
  637. # list(some_list) is done to preserve the existing list
  638. some_list = [unicode(s) for s in list(some_list)]
  639. if not some_list:
  640. return ""
  641. elif len(some_list) == 1:
  642. return some_list[0]
  643. else:
  644. some_list = ["'%s'" % s for s in some_list]
  645. return ", ".join(some_list[:-1]) + sep + some_list[-1]
  646. else:
  647. return some_list
  648. def filter_strip_join(some_list, sep):
  649. """given a list, filter None values, strip spaces and join"""
  650. return (cstr(sep)).join((cstr(a).strip() for a in filter(None, some_list)))
  651. def get_path(*path):
  652. import os
  653. return os.path.join(get_base_path(), *path)
  654. def get_base_path():
  655. import conf
  656. import os
  657. return os.path.dirname(os.path.abspath(conf.__file__))
  658. def get_url_to_form(doctype, name, base_url=None, label=None):
  659. if not base_url:
  660. try:
  661. from startup import get_url
  662. base_url = get_url()
  663. except ImportError:
  664. base_url = get_request_site_address()
  665. if not label: label = name
  666. return """<a href="%(base_url)s/app.html#!Form/%(doctype)s/%(name)s">%(label)s</a>""" % locals()
  667. def encode_dict(d, encoding="utf-8"):
  668. for key in d:
  669. if isinstance(d[key], basestring) and isinstance(d[key], unicode):
  670. d[key] = d[key].encode(encoding)
  671. return d
  672. def decode_dict(d, encoding="utf-8"):
  673. for key in d:
  674. if isinstance(d[key], basestring) and not isinstance(d[key], unicode):
  675. d[key] = d[key].decode(encoding, "ignore")
  676. return d
  677. import operator
  678. operator_map = {
  679. # startswith
  680. "^": lambda (a, b): (a or "").startswith(b),
  681. # in or not in a list
  682. "in": lambda (a, b): operator.contains(b, a),
  683. "not in": lambda (a, b): not operator.contains(b, a),
  684. # comparison operators
  685. "=": lambda (a, b): operator.eq(a, b),
  686. "!=": lambda (a, b): operator.ne(a, b),
  687. ">": lambda (a, b): operator.gt(a, b),
  688. "<": lambda (a, b): operator.lt(a, b),
  689. ">=": lambda (a, b): operator.ge(a, b),
  690. "<=": lambda (a, b): operator.le(a, b),
  691. "not None": lambda (a, b): a and True or False,
  692. "None": lambda (a, b): (not a) and True or False
  693. }
  694. def compare(val1, condition, val2):
  695. if condition in operator_map:
  696. return operator_map[condition]((val1, val2))
  697. return False