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 ;)
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.
A slug is a short label for something, containing only letters, numbers, underscores or hyphens. They're generally used in URLs."
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With