how to unescape special characters in django urlpatterns

末鹿安然 提交于 2019-12-12 05:21:20

问题


So, suppose I have a django app which needs to respond to a url like this: http://127.0.0.1:8000/food%20log/4/up/ . The original parameter is "food log", but it needed to have the space replaced with %20 when it was included in the url. Now the link has been clicked on, and it's coming back to urls.py.

urlpatterns = patterns('',
(r'^(?P<content_type>\w+)/(?P<object_id>\d+)/(?P<direction>up|down|clear)/$', process_vote),

... )

So, it appears that it is not able to properly recognize the parameter . This is functional code prior to wanting to use a content_type which has a space in it. If we assume for the moment that I can't just remove the space from the name of that content_type throughout the rest of the system, how do I get the urlpatterns function to recognize that "food%20log" is actually "food log", so that it will recognize it as a valid ?

Basically I want to preprocess the string before it's acted on by urlpatterns, but I am not sure how/where to do that. Thanks for any assistance.


回答1:


According to the Python manual for the re module:

When the LOCALE and UNICODE flags are not specified, matches any alphanumeric character and the underscore; this is equivalent to the set [a-zA-Z0-9_]. With LOCALE, it will match the set [0-9_] plus whatever characters are defined as alphanumeric for the current locale. If UNICODE is set, this will match the characters [0-9_] plus whatever is classified as alphanumeric in the Unicode character properties database.

So maybe include the space in the regular expression in addition to \w.

urlpatterns = patterns('',
(r'^(?P<content_type>[\w ]+)/(?P<object_id>\d+)/(?P<direction>up|down|clear)/$',     process_vote),


来源:https://stackoverflow.com/questions/7275203/how-to-unescape-special-characters-in-django-urlpatterns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!