基于语言的URL和数据库路由 [英] URL and database routing based on language

查看:68
本文介绍了基于语言的URL和数据库路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网址格式如下:

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

我需要做:
1.根据语言代码,如果不支持语言代码,我想选择合适的数据库或加Http404.
2.我希望将语言代码最好保存在请求对象中,以便可以在模板中访问它.
3.我希望我的urls.py看起来不像这样:

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')

但是:

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

因此django将完全忽略URL中的语言代码.

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

任何人都可以告诉我django是否可行,还是我应该寻找其他解决方案?

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

推荐答案

我设法弄清楚了这一点.首先,您需要阅读以下文档: https://docs.djangoproject. com/en/dev/topics/i18n/translation/

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-我基于 http://djangosnippets.org/snippets/2037/<编写了自己的中间件/a>(将这个中间件放在MIDDLEWARE_CLASSES列表中的第一个中间件是至关重要的)

@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-可以使用request.LANGUAGE_CODE

@ 3-在文档中进行了说明: https://docs.djangoproject.com/en/dev/topics/i18n/translation/#internationalization-in-url-patterns

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

这篇关于基于语言的URL和数据库路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆