使用中间件排除 Django 应用程序的本地化
我需要本地化 django 项目,但仅保留其中一个应用程序(博客)为英语。
我编写这个中间件是为了实现此目的:
from django.conf import settings
from django.core.urlresolvers import resolve
class DelocalizeMiddleware:
def process_request(self, request):
current_app_name = __name__.split('.')[-2]
match = resolve(request.path)
if match.app_name == current_app_name:
request.LANGUAGE_CODE = settings.LANGUAGE_CODE
问题是,它假设中间件直接位于应用程序模块中(例如 blog/middleware.py),用于检索应用程序名称。其他项目可能在 blog/middleware/delocalize.py 或其他东西中包含中间件。
检索当前正在运行的应用程序的名称的最佳方法是什么?
I need to localize a django project, but keep one of the applications (the blog) English only.
I wrote this middleware in order to achieve this:
from django.conf import settings
from django.core.urlresolvers import resolve
class DelocalizeMiddleware:
def process_request(self, request):
current_app_name = __name__.split('.')[-2]
match = resolve(request.path)
if match.app_name == current_app_name:
request.LANGUAGE_CODE = settings.LANGUAGE_CODE
Problem is, it assumes the middleware lies directly in the application module (e.g. blog/middleware.py) for retrieving the app name. Other projects might have the middleware in blog/middleware/delocalize.py or something else altogether.
What's the best way to retrieve the name of the currently running app?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 Django 的
resolve
函数来获取当前应用程序名称。https://docs.djangoproject.com/en/dev/topics/ http/urls/#resolve
You can use Django's
resolve
function to get the current app name.https://docs.djangoproject.com/en/dev/topics/http/urls/#resolve