Supplement existing urlpatterns with corresponding patterns that also include a '.format' suffix. Retains urlpattern ordering. urlpatterns: A list of URL patterns. suffix_required: If `True`, only suffixed URLs will be generated, and non-suffixed URLs will
(urlpatterns, suffix_required=False, allowed=None)
| 83 | |
| 84 | |
| 85 | def format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None): |
| 86 | """ |
| 87 | Supplement existing urlpatterns with corresponding patterns that also |
| 88 | include a '.format' suffix. Retains urlpattern ordering. |
| 89 | |
| 90 | urlpatterns: |
| 91 | A list of URL patterns. |
| 92 | |
| 93 | suffix_required: |
| 94 | If `True`, only suffixed URLs will be generated, and non-suffixed |
| 95 | URLs will not be used. Defaults to `False`. |
| 96 | |
| 97 | allowed: |
| 98 | An optional tuple/list of allowed suffixes. eg ['json', 'api'] |
| 99 | Defaults to `None`, which allows any suffix. |
| 100 | """ |
| 101 | suffix_kwarg = api_settings.FORMAT_SUFFIX_KWARG |
| 102 | if allowed: |
| 103 | if len(allowed) == 1: |
| 104 | allowed_pattern = allowed[0] |
| 105 | else: |
| 106 | allowed_pattern = '(%s)' % '|'.join(allowed) |
| 107 | suffix_pattern = r'\.(?P<%s>%s)/?$' % (suffix_kwarg, allowed_pattern) |
| 108 | else: |
| 109 | suffix_pattern = r'\.(?P<%s>[a-z0-9]+)/?$' % suffix_kwarg |
| 110 | |
| 111 | converter_name = _generate_converter_name(allowed) |
| 112 | if converter_name not in get_converters(): |
| 113 | suffix_converter = _get_format_path_converter(allowed) |
| 114 | register_converter(suffix_converter, converter_name) |
| 115 | |
| 116 | suffix_route = '<%s:%s>' % (converter_name, suffix_kwarg) |
| 117 | |
| 118 | return apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required, suffix_route) |