views:

42

answers:

1

I have a web application which will return a user id based on the first segment of the url, much like Twitter:

http://www.myapplication.com/user-name-goes-here/

It can go deeper too, like so:

http://www.myapplication.com/user-name-goes-here/news/article_1/

In order to break the site down, I am using the following URL routing technique:

(r'^(?P<slug>\w+)/', include('myapp.sites.urls')),

This will then further route the user to the correct page, but as it stands I am having to query the database in every view in order to obtain the user_id based on the first url segment. I was hoping to somehow automate this so I don't have to bloat my views with the same code each time... my solution was to create some middleware which checks the url segment and returns a 404 if its not found:

    from django.http import Http404

class DomainMiddleware(object):
    def process_request(self, request):
        from myapp.sites.models import Sites

        dname = request.path.split('/')[1]
        if not dname:
            return
        try:
            d = Sites.objects.get(domain__exact=dname)
        except Sites.DoesNotExist:
            raise Http404

        return

This works, but it's trying to parse EVERY request, even those to images, favicons etc.

My question is thus; Is there a way to run this query on every page load without clogging up my views with extra code? If middleware is the solution, how can I modify my code so that it doesn't include EVERY request, only those to successfully routed URLs?

Hope someone can help!

+2  A: 

The Django server shouldn't be processing requests for static content URLs - certainly not in production anyway, where you'd have a different web server running to handle that, so this shouldn't be an issue there.

But if you say you'd like this to run for only sucessfully routed URLs, maybe you'd be better of using process_view rather than process_request in your middleware? http://docs.djangoproject.com/en/dev/topics/http/middleware/#process-view

process_view works at view level rather than request level, and provides a view_func argument which you can check so that your code doesn't run when it's the django.views.static.serve view used for serving static media during development.

Whatever happens you should defs be caching that database call if it's going to be used on every view.

Rolo
Thanks a lot for your reply, really helpful. I'll most definitely be caching the query, but obviously I need to make sure it's run at least once, especially if you land further into the users page (which is why I need it to run on every view). Cheers!
Hanpan