jsrouting.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. # -*- coding: utf-8 -*-
  2. """
  3. werkzeug.contrib.jsrouting
  4. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  5. Addon module that allows to create a JavaScript function from a map
  6. that generates rules.
  7. :copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details.
  8. :license: BSD, see LICENSE for more details.
  9. """
  10. try:
  11. from simplejson import dumps
  12. except ImportError:
  13. try:
  14. from json import dumps
  15. except ImportError:
  16. def dumps(*args):
  17. raise RuntimeError('simplejson required for jsrouting')
  18. from inspect import getmro
  19. from werkzeug.routing import NumberConverter
  20. from werkzeug._compat import iteritems
  21. def render_template(name_parts, rules, converters):
  22. result = u''
  23. if name_parts:
  24. for idx in range(0, len(name_parts) - 1):
  25. name = u'.'.join(name_parts[:idx + 1])
  26. result += u"if (typeof %s === 'undefined') %s = {}\n" % (name, name)
  27. result += '%s = ' % '.'.join(name_parts)
  28. result += """(function (server_name, script_name, subdomain, url_scheme) {
  29. var converters = [%(converters)s];
  30. var rules = %(rules)s;
  31. function in_array(array, value) {
  32. if (array.indexOf != undefined) {
  33. return array.indexOf(value) != -1;
  34. }
  35. for (var i = 0; i < array.length; i++) {
  36. if (array[i] == value) {
  37. return true;
  38. }
  39. }
  40. return false;
  41. }
  42. function array_diff(array1, array2) {
  43. array1 = array1.slice();
  44. for (var i = array1.length-1; i >= 0; i--) {
  45. if (in_array(array2, array1[i])) {
  46. array1.splice(i, 1);
  47. }
  48. }
  49. return array1;
  50. }
  51. function split_obj(obj) {
  52. var names = [];
  53. var values = [];
  54. for (var name in obj) {
  55. if (typeof(obj[name]) != 'function') {
  56. names.push(name);
  57. values.push(obj[name]);
  58. }
  59. }
  60. return {names: names, values: values, original: obj};
  61. }
  62. function suitable(rule, args) {
  63. var default_args = split_obj(rule.defaults || {});
  64. var diff_arg_names = array_diff(rule.arguments, default_args.names);
  65. for (var i = 0; i < diff_arg_names.length; i++) {
  66. if (!in_array(args.names, diff_arg_names[i])) {
  67. return false;
  68. }
  69. }
  70. if (array_diff(rule.arguments, args.names).length == 0) {
  71. if (rule.defaults == null) {
  72. return true;
  73. }
  74. for (var i = 0; i < default_args.names.length; i++) {
  75. var key = default_args.names[i];
  76. var value = default_args.values[i];
  77. if (value != args.original[key]) {
  78. return false;
  79. }
  80. }
  81. }
  82. return true;
  83. }
  84. function build(rule, args) {
  85. var tmp = [];
  86. var processed = rule.arguments.slice();
  87. for (var i = 0; i < rule.trace.length; i++) {
  88. var part = rule.trace[i];
  89. if (part.is_dynamic) {
  90. var converter = converters[rule.converters[part.data]];
  91. var data = converter(args.original[part.data]);
  92. if (data == null) {
  93. return null;
  94. }
  95. tmp.push(data);
  96. processed.push(part.name);
  97. } else {
  98. tmp.push(part.data);
  99. }
  100. }
  101. tmp = tmp.join('');
  102. var pipe = tmp.indexOf('|');
  103. var subdomain = tmp.substring(0, pipe);
  104. var url = tmp.substring(pipe+1);
  105. var unprocessed = array_diff(args.names, processed);
  106. var first_query_var = true;
  107. for (var i = 0; i < unprocessed.length; i++) {
  108. if (first_query_var) {
  109. url += '?';
  110. } else {
  111. url += '&';
  112. }
  113. first_query_var = false;
  114. url += encodeURIComponent(unprocessed[i]);
  115. url += '=';
  116. url += encodeURIComponent(args.original[unprocessed[i]]);
  117. }
  118. return {subdomain: subdomain, path: url};
  119. }
  120. function lstrip(s, c) {
  121. while (s && s.substring(0, 1) == c) {
  122. s = s.substring(1);
  123. }
  124. return s;
  125. }
  126. function rstrip(s, c) {
  127. while (s && s.substring(s.length-1, s.length) == c) {
  128. s = s.substring(0, s.length-1);
  129. }
  130. return s;
  131. }
  132. return function(endpoint, args, force_external) {
  133. args = split_obj(args);
  134. var rv = null;
  135. for (var i = 0; i < rules.length; i++) {
  136. var rule = rules[i];
  137. if (rule.endpoint != endpoint) continue;
  138. if (suitable(rule, args)) {
  139. rv = build(rule, args);
  140. if (rv != null) {
  141. break;
  142. }
  143. }
  144. }
  145. if (rv == null) {
  146. return null;
  147. }
  148. if (!force_external && rv.subdomain == subdomain) {
  149. return rstrip(script_name, '/') + '/' + lstrip(rv.path, '/');
  150. } else {
  151. return url_scheme + '://'
  152. + (rv.subdomain ? rv.subdomain + '.' : '')
  153. + server_name + rstrip(script_name, '/')
  154. + '/' + lstrip(rv.path, '/');
  155. }
  156. };
  157. })""" % {'converters': u', '.join(converters),
  158. 'rules': rules}
  159. return result
  160. def generate_map(map, name='url_map'):
  161. """
  162. Generates a JavaScript function containing the rules defined in
  163. this map, to be used with a MapAdapter's generate_javascript
  164. method. If you don't pass a name the returned JavaScript code is
  165. an expression that returns a function. Otherwise it's a standalone
  166. script that assigns the function with that name. Dotted names are
  167. resolved (so you an use a name like 'obj.url_for')
  168. In order to use JavaScript generation, simplejson must be installed.
  169. Note that using this feature will expose the rules
  170. defined in your map to users. If your rules contain sensitive
  171. information, don't use JavaScript generation!
  172. """
  173. from warnings import warn
  174. warn(DeprecationWarning('This module is deprecated'))
  175. map.update()
  176. rules = []
  177. converters = []
  178. for rule in map.iter_rules():
  179. trace = [{
  180. 'is_dynamic': is_dynamic,
  181. 'data': data
  182. } for is_dynamic, data in rule._trace]
  183. rule_converters = {}
  184. for key, converter in iteritems(rule._converters):
  185. js_func = js_to_url_function(converter)
  186. try:
  187. index = converters.index(js_func)
  188. except ValueError:
  189. converters.append(js_func)
  190. index = len(converters) - 1
  191. rule_converters[key] = index
  192. rules.append({
  193. u'endpoint': rule.endpoint,
  194. u'arguments': list(rule.arguments),
  195. u'converters': rule_converters,
  196. u'trace': trace,
  197. u'defaults': rule.defaults
  198. })
  199. return render_template(name_parts=name and name.split('.') or [],
  200. rules=dumps(rules),
  201. converters=converters)
  202. def generate_adapter(adapter, name='url_for', map_name='url_map'):
  203. """Generates the url building function for a map."""
  204. values = {
  205. u'server_name': dumps(adapter.server_name),
  206. u'script_name': dumps(adapter.script_name),
  207. u'subdomain': dumps(adapter.subdomain),
  208. u'url_scheme': dumps(adapter.url_scheme),
  209. u'name': name,
  210. u'map_name': map_name
  211. }
  212. return u'''\
  213. var %(name)s = %(map_name)s(
  214. %(server_name)s,
  215. %(script_name)s,
  216. %(subdomain)s,
  217. %(url_scheme)s
  218. );''' % values
  219. def js_to_url_function(converter):
  220. """Get the JavaScript converter function from a rule."""
  221. if hasattr(converter, 'js_to_url_function'):
  222. data = converter.js_to_url_function()
  223. else:
  224. for cls in getmro(type(converter)):
  225. if cls in js_to_url_functions:
  226. data = js_to_url_functions[cls](converter)
  227. break
  228. else:
  229. return 'encodeURIComponent'
  230. return '(function(value) { %s })' % data
  231. def NumberConverter_js_to_url(conv):
  232. if conv.fixed_digits:
  233. return u'''\
  234. var result = value.toString();
  235. while (result.length < %s)
  236. result = '0' + result;
  237. return result;''' % conv.fixed_digits
  238. return u'return value.toString();'
  239. js_to_url_functions = {
  240. NumberConverter: NumberConverter_js_to_url
  241. }