开发者

Middleware to check existence of domain in Django

I have a single application which manages and delivers several sites. I does this by determining which domain to serve from the URL:

http://myapplication.com/site_1/ or http://myapplication.com/site_2/

Each site obviously has it's own pages, so might end up with a url like this:

http://myapplication.com/site_1/contact_us/

What I'd like to do is create some middleware which, when a url such as the two above (http://myapplication.com/somedomainhere) it will check the existence of that particular domain in a database (which I have already created) and, if it exists, continue to the index view. If the domain doesn't exist, I want to divert to a 404 page.

Is this something which is r开发者_JAVA技巧elatively simple to do with middleware and if so, does anyone have any examples of how I might go about accomplishing this?

I am aware of the Sites framework which comes with Django, but I will be using the above to create something slightly different.


    class MyMiddleware():
    def process_request(self, request):
        app_name = request.path.split('/')[0]

        try:
            app = Apps.objects.get(name=app_name)
        except DoesNotExist:
            return

        request.urlconf = app.urlconf
        return

The include your middleware in your settings.py with all the rest.

This assumes that your app model includes a property that knows about the urlconf for that app. Just point the request at that urlconf, and Django takes care of the rest.

For reference, see the documentation on middleware, request processing and setting the urlconfs.

Hope this helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜