From 38ce5a91ac26f41e2b70ab087635a5c9c2de37da Mon Sep 17 00:00:00 2001 From: Qi Cui <67538306+Qi-Cui@users.noreply.github.com> Date: Fri, 9 Aug 2024 11:12:06 +0800 Subject: [PATCH] feat(locale): add time zone adaptation according to tenant user setting (#1871) --- .../bkuser/apis/web/personal_center/views.py | 1 + src/bk-user/bkuser/common/middlewares.py | 18 ++++++++++++++++++ src/bk-user/bkuser/settings.py | 1 + 3 files changed, 20 insertions(+) diff --git a/src/bk-user/bkuser/apis/web/personal_center/views.py b/src/bk-user/bkuser/apis/web/personal_center/views.py index 84113d7ef..bf388e82c 100644 --- a/src/bk-user/bkuser/apis/web/personal_center/views.py +++ b/src/bk-user/bkuser/apis/web/personal_center/views.py @@ -8,6 +8,7 @@ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ + from typing import Dict from django.utils.translation import gettext_lazy as _ diff --git a/src/bk-user/bkuser/common/middlewares.py b/src/bk-user/bkuser/common/middlewares.py index 4c3b705aa..219ca8704 100644 --- a/src/bk-user/bkuser/common/middlewares.py +++ b/src/bk-user/bkuser/common/middlewares.py @@ -8,6 +8,10 @@ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ + +import pytz +from django.utils import timezone + from .local import local @@ -29,3 +33,17 @@ def __call__(self, request): local.release() return response + + +class TimeZoneMiddleware: + def __init__(self, get_response): + self.get_response = get_response + + def __call__(self, request): + # 如果时区非空,则激活当前时区。如果时区为空,则使用默认时区 + if request.user and request.user.is_authenticated and (tzname := request.user.get_property("time_zone")): + timezone.activate(pytz.timezone(tzname)) + else: + timezone.deactivate() + + return self.get_response(request) diff --git a/src/bk-user/bkuser/settings.py b/src/bk-user/bkuser/settings.py index 149d94aa6..b7be2bc79 100644 --- a/src/bk-user/bkuser/settings.py +++ b/src/bk-user/bkuser/settings.py @@ -73,6 +73,7 @@ "django.middleware.clickjacking.XFrameOptionsMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", "bkuser.auth.middlewares.LoginMiddleware", + "bkuser.common.middlewares.TimeZoneMiddleware", "django_prometheus.middleware.PrometheusAfterMiddleware", ]