Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django- pass a string or an instance in urls.py?

Is there a benefit to passing a string in your url patters vs a function instance? It seems like it could be optimized to not actually load the function until it is needed, but is this in fact true?

from django.conf.urls.defaults import *
from myapp.views import myView

urlpatterns = patterns('',
    # as a string
    url(r'^as-string/$', "myapp.views.myView"),

    # Uploading photos
    url(r'^as-instance/$', myView),

)

edit: If it's true that it doesn't import until they're needed, then it would be an optimization for memory, but non-existant functions and other errors would not be raised until you actually try to visit the url.

Of course that isn't an issue if you write tests though ;)

like image 810
Jiaaro Avatar asked Jun 19 '09 15:06

Jiaaro


People also ask

How can we handle URLs in Django?

Django provides tools for performing URL reversing that match the different layers where URLs are needed: In templates: Using the url template tag. In Python code: Using the reverse() function. In higher level code related to handling of URLs of Django model instances: The get_absolute_url() method.

What is slug in Django URLs?

A slug is a short label for something, containing only letters, numbers, underscores or hyphens. They're generally used in URLs."

What is dynamic URL in Django?

Being able to capture one or more values from a given URL during an HTTP request is an important feature Django offers developers. We already saw a little bit about how Django routing works, but those examples used hard-coded URL patterns. While this does work, it does not scale.


2 Answers

The main benefit is that when you're working with the actual callable object you can do things like apply decorators to it in the URLConf. So you can do things like:

from django.conf.urls.defaults import *
from django.contrib.auth.decorators import login_required

from some_module import some_view

urlpatterns = patterns('',
                       (r'^some_url/$', some_view),
                       (r'^some_other_url/$', login_required(some_view)))

etc.

This lets you have decorators which are only applied to a view when you specifically want them to, rather than decorating in the views file and then having to live with it always having that decorator applied.

like image 197
James Bennett Avatar answered Oct 04 '22 04:10

James Bennett


Perusing the source to RegexURLPattern (which is what defaults.url is using under the covers) confirms that the import only happens when and if needed, and so your ideas are correct: it's a slight optimization but does require thorough tests!

like image 32
Alex Martelli Avatar answered Oct 04 '22 03:10

Alex Martelli