Created
September 23, 2016 14:56
-
-
Save kwatch/a126f126c3440e1c9194307f9f826abf to your computer and use it in GitHub Desktop.
r'/foo/<id:\d+>.json' を r'^/foo(?P<id>\d+)\.json$' へと変換するサンプルコード
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
## license: public domain | |
import re | |
URLPATH_PARAM_PATTERN = r'<(\w+)(?::(.*?))?>' | |
re_escape = lambda s: re.escape(s).replace(r'\/', '/') | |
def compile_urlpath(urlpath, default_pat='[^/]'): | |
buf = ['^']; add = buf.append | |
pos = 0 | |
for m in re.finditer(URLPATH_PARAM_PATTERN, urlpath): | |
text = urlpath[pos:m.start(0)] | |
add(re_escape(text)) | |
pos = m.end(0) | |
name, pat = m.groups() | |
add("(?P<%s>%s)" % (name, pat or default_pat)) | |
add(re_escape(urlpath[pos:])) | |
add('$') | |
return "".join(buf) | |
if __name__ == '__main__': | |
urlpath = r'/api/posts/<slug>/comments/<comment_id:\d+>.json' | |
result = compile_urlpath(urlpath) | |
print(repr(result)) | |
#=> r'^/api/posts/(?P<slug>[^/]+)/comments/(?P<comment_id>\d+)\.json$' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment