Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

django - URL and database routing based on language

I have URLs in the following form:

http://example.com/[language_code]/xxx

I need to do:
1. Based on the language code, I want to select appropriate DB or raise Http 404 if language code is not supported.
2. I'd like to save the language code in the request object preferably, so I can access it in my templates.
3. I'd like my urls.py don't look like this:

url(r'^(?P<lang>w+)/xxx/$', 'my_app.views.xxx')

but rather:

url(r'^xxx/$', 'my_app.views.xxx')

so django will completely ignore the language code in the URL.

Can anyone tell me please if this is doable with django or I should look for another solution?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I managed to figure this out. First of all you need to read the docs: https://docs.djangoproject.com/en/dev/topics/i18n/translation/

@1 - I wrote my own middleware based on http://djangosnippets.org/snippets/2037/ (it's crucial to put this middleware as the first one in the MIDDLEWARE_CLASSES list)

import threading
from django.http import Http404
from django.conf import settings

request_cfg = threading.local()


class RouterMiddleware(object):
    def process_view(self, request, view_func, view_args, view_kwargs):
        lang = request.LANGUAGE_CODE
        if lang in settings.LANGUAGES:
            request_cfg.lang = lang
        else:
            raise Http404()

    def process_response(self, request, response):
        if hasattr(request_cfg, 'lang'):
            del request_cfg.lang
        return response


class DatabaseRouter(object):
    def _default_db(self):
        if hasattr(request_cfg, 'lang') and request_cfg.lang in settings.DATABASES:
            return request_cfg.lang
        else:
            return 'default'

    def db_for_read(self, model, **hints):
        return self._default_db()

    def db_for_write(self, model, **hints):
        return self._default_db()

@2 - Can be accessed using request.LANGUAGE_CODE

@3 - It's explained in docs: https://docs.djangoproject.com/en/dev/topics/i18n/translation/#internationalization-in-url-patterns


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...