PageRenderTime 27ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/src/htsql_tweak/shell/default/act.py

https://bitbucket.org/prometheus/htsql/
Python | 75 lines | 67 code | 4 blank | 4 comment | 0 complexity | 745af0342cc2390b32fa348d49b43e78 MD5 | raw file
Possible License(s): AGPL-1.0, Unlicense
  1. #
  2. # Copyright (c) 2006-2011, Prometheus Research, LLC
  3. # See `LICENSE` for license information, `AUTHORS` for the list of authors.
  4. #
  5. from htsql.context import context
  6. from htsql.adapter import adapts
  7. from htsql.cmd.act import Act, RenderAction, act
  8. from htsql.cmd.command import UniversalCmd, DefaultCmd
  9. from ..command import ShellCmd
  10. from htsql.tr.error import TranslateError
  11. from htsql.tr.parse import parse
  12. from htsql.tr.bind import bind
  13. from htsql.tr.lookup import lookup_command
  14. import re
  15. escape_pattern = r"""%(?:(?P<code>[0-9A-Fa-f]{2})|..)"""
  16. escape_regexp = re.compile(escape_pattern)
  17. def unquote(query):
  18. def replace(match):
  19. code = match.group('code')
  20. if not code:
  21. return match.group()
  22. code = int(code, 16)
  23. if code == 0x00:
  24. return match.group()
  25. return chr(code)
  26. return escape_regexp.sub(replace, query)
  27. class ShellRenderUniversal(Act):
  28. adapts(UniversalCmd, RenderAction)
  29. def __call__(self):
  30. addon = context.app.tweak.shell.default
  31. command = None
  32. accept = set()
  33. if 'HTTP_ACCEPT' in self.action.environ:
  34. for name in self.action.environ['HTTP_ACCEPT'].split(','):
  35. if ';' in name:
  36. name = name.split(';', 1)[0]
  37. name = name.strip()
  38. accept.add(name)
  39. if not (('text/html' in accept or 'text/*' in accept
  40. or '*/*' in accept) and 'application/json' not in accept):
  41. return super(ShellRenderUniversal, self).__call__()
  42. try:
  43. syntax = parse(self.command.query)
  44. if addon.on_root and syntax.segment.branch is None:
  45. command = ShellCmd(is_implicit=True)
  46. else:
  47. binding = bind(syntax)
  48. command = lookup_command(binding)
  49. if command is None:
  50. if (addon.on_default and
  51. syntax.segment.branch is not None):
  52. query = unquote(self.command.query)
  53. query = query.decode('utf-8', 'replace')
  54. command = ShellCmd(query, is_implicit=True)
  55. else:
  56. command = DefaultCmd(binding)
  57. return act(command, self.action)
  58. except TranslateError:
  59. if not addon.on_error:
  60. raise
  61. query = unquote(self.command.query)
  62. query = query.decode('utf-8', 'replace')
  63. command = ShellCmd(query, is_implicit=True)
  64. return act(command, self.action)