Skip to content

Instantly share code, notes, and snippets.

@jamiecounsell
Created October 3, 2015 20:56
Show Gist options
  • Save jamiecounsell/7956fd89869c327a0310 to your computer and use it in GitHub Desktop.
Save jamiecounsell/7956fd89869c327a0310 to your computer and use it in GitHub Desktop.
Django urlpatterns to dictionary for easy JSON serialization (redacting `/admin/` urls)
def recursively_build__url_dict(d, urlpatterns):
for i in urlpatterns:
if isinstance(i, RegexURLResolver):
d[str(i.__dict__['_regex'])] = {}
if str(i.__dict__['_regex']) != "^admin/":
recursively_build__url_dict(
d[str(i.__dict__['_regex'])], i.url_patterns
)
else:
d[str(i.__dict__['_regex'])] = "REDACTED"
elif isinstance(i, RegexURLPattern):
d[str(i.regex.pattern)] = i.callback.__name__
@jamiecounsell
Copy link
Author

Just call it

@api_view() # <- djangorestframework
def urls_as_view(request):
    a = {}
    recursively_build__url_dict(a, core.urls.urlpatterns)
    return HttpResponse(
        json.dumps(a, sort_keys=True, indent=4, separators=(',', ': ')),
        content_type="application/json")

And the response will be something like:

{
    "^$": "index",
    "^admin/": "REDACTED",
    "^api/": {
        "^$": "urls_as_view",
        "^token-auth/": {
            "^$": "RootView",
            "^activate/$": "ActivationView",
            "^me/$": "UserView",
            "^password/$": "SetPasswordView",
            "^password/reset/$": "PasswordResetView",
            "^password/reset/confirm/$": "PasswordResetConfirmView",
            "^register/$": "RegistrationView",
            "^username/$": "SetUsernameView"
        },
        "^myModel/(?P<pk>[0-9]+)/$": "myModelRequestView",
        "^myModel/new/$": "myModelCreateView",
        "^myOtherModel/$": "myOtherModelListView",
        "^myOtherModel/(?P<pk>[0-9]+)/$": "myOtherModelView",
        "^myOtherModel/new/$": "myOtherModelCreateView"
    },
    "^session-auth/": {
        "^login/$": "login",
        "^logout/$": "logout"
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment