utils.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. # -*- coding: utf-8 -*-
  2. """Helper utilities and decorators."""
  3. from __future__ import print_function
  4. import sys
  5. import time
  6. from datetime import datetime
  7. import os
  8. import re
  9. from flask import flash
  10. from invoke import Responder
  11. def flash_errors(form, category='warning'):
  12. """Flash all errors for a form."""
  13. for field, errors in form.errors.items():
  14. for error in errors:
  15. flash('{0} - {1}'.format(getattr(form, field).label.text, error), category)
  16. def date_str_to_obj(ymd):
  17. return time.strptime(ymd, '%Y-%m-%d')
  18. def datetime_str_to_obj(ymd_his):
  19. return datetime.strptime(ymd_his, "%Y-%m-%d %H:%i:%s")
  20. PY2 = int(sys.version[0]) == 2
  21. if PY2:
  22. text_type = unicode # noqa
  23. binary_type = str
  24. string_types = (str, unicode) # noqa
  25. unicode = unicode # noqa
  26. basestring = basestring # noqa
  27. reload(sys)
  28. sys.setdefaultencoding('utf8')
  29. else:
  30. text_type = str
  31. binary_type = bytes
  32. string_types = (str,)
  33. unicode = str
  34. basestring = (str, bytes)
  35. def detailtrace():
  36. from flask import current_app
  37. retStr = ""
  38. f = sys._getframe()
  39. f = f.f_back
  40. while hasattr(f, "f_code"):
  41. co = f.f_code
  42. retStr = "->%s(%s:%s)\n" % (os.path.basename(co.co_filename),
  43. co.co_name,
  44. f.f_lineno) + retStr
  45. f = f.f_back
  46. current_app.logger.info(retStr)
  47. print(retStr)
  48. def color_clean(text_with_color):
  49. '''
  50. e.g \x1b[?1h\x1b=
  51. e.g \x1b[?1l\x1b>
  52. @param text_with_color:
  53. @return:
  54. '''
  55. pure_text = text_with_color.strip()
  56. pure_text = re.sub('\x1B\[[0-9;]*[mGK]', '', pure_text, flags=re.I)
  57. pure_text = re.sub('\x1B\[\?[0-9;]*[a-z]\x1B[=><]', '', pure_text, flags=re.I)
  58. return pure_text.strip()
  59. def say_yes():
  60. return Responder(
  61. pattern=r'yes/no',
  62. response='yes\n',
  63. )
  64. def excludes_format(excludes_string):
  65. excludes = [i for i in excludes_string.split('\n') if i.strip()]
  66. if not excludes:
  67. return ''
  68. excludes = ' --exclude='.join(excludes)
  69. return ' --exclude=' + excludes