我在我的Django应用程序中使用Ploly Python.我的网络应用程序中有两个主题:黑暗和Illuminate . 如果 Select 浅色主题,图表背景为白色,而对于深色主题,图表背景设置为黑色.这可以分别使用Dark_Theme_Template和light_Theme_Template中的以下代码来完成.

我得到的问题是,当一个用户更改主题时,当另一个用户刷新或回调被击中时,它会影响另一个用户的图表.

dark theme template

import plotly.io as pio
from plotly.graph_objs import Layout
import plotly.graph_objects as go

dark_template_layout = Layout(
    paper_bgcolor="black",
    plot_bgcolor="black",
    # other dark theme settings ...
)


dark_template = go.layout.Template()
dark_template.layout = dark_template_layout


light theme template

import plotly.io as pio
from plotly.graph_objs import Layout
import plotly.graph_objects as go

white_template_layout = Layout(
    paper_bgcolor="white",
    plot_bgcolor="white",
    # further light theme settings ...
)


white_template = go.layout.Template()
white_template.layout = white_template_layout

设置模板并将黑色主题设置为默认设置

import plotly.io as pio
from plotly.graph_objs import Layout
import plotly.graph_objects as go


from apps.dashboards.themes.dark_theme import dark_template
from apps.dashboards.themes.white_theme import white_template


pio.templates["white_template"] = white_template
pio.templates["dark_template"] = dark_template

pio.templates.default = "dark_template"

当用户更改主题时,此视图被调用

class ChangeTheme(View):
    def post(self, request):
        response = {}
        try:
            light_mode = True if request.POST.get("light_mode") == "true" else False
            if light_mode:
                request.session["light_mode"] = True
                request.session.save()

                pio.templates.default = "white_template"

            else:
                request.session["light_mode"] = False
                request.session.save()
                
                pio.templates.default = "dark_template"

        except Exception as error:

        return HttpResponse(json.dumps(response), content_type="application/json")

我知道pio.template.default=‘’是导致问题的原因,因为它是跨应用程序全局设置的.因此,当另一个用户更改主题时,系统上的所有其他用户都会更改.

要确保每个用户的主题偏好独立于其他用户,为不同的用户维护不同的主题而不受全局干扰,推荐的最佳实践是什么?我如何重构我的代码来实现这一点? 首先感谢您的帮助!

推荐答案

我知道pio.template.default = ''是导致这个问题的原因,因为它是跨应用程序全局设置的.

True:这意味着对它的任何更改都会影响所有用户,无论他们的个人主题偏好如何.

建议的最佳实践是将全局缺省值更改为not,但在呈现图表时根据用户的主题首选项 for each 图表动态设置模板.

Store each user's theme preference in their session or a profile model in the database.
When rendering a chart for a user, fetch their theme preference and apply the appropriate theme.

在这里,我将使用在GibbsConsulting/django-plotly-dash issue 67GibbsConsulting/django-plotly-dash/demo/demo/views.py中提到的会话

首先,要将ChangeTheme视图更新为仅存储用户的首选项,而不修改全局设置:

class ChangeTheme(View):
    def post(self, request):
        response = {}
        try:
            light_mode = True if request.POST.get("light_mode") == "true" else False
            request.session["light_mode"] = light_mode
            request.session.save()

        except Exception as error:
            # handle error

        return HttpResponse(json.dumps(response), content_type="application/json")

Then you dynamically apply the theme when rendering a chart.
Let's assume, for instance, that you have a function/view render_chart that creates and returns a chart. Update this function to use the user-specific template:

def render_chart(request):

    # Retrieve user's theme preference
    light_mode = request.session.get("light_mode", False)
    
    # Create chart
    fig = go.Figure()
    
    # Based on the user preference, apply the correct theme
    if light_mode:
        fig.update_layout(template="white_template")
    else:
        fig.update_layout(template="dark_template")

    # rest of the chart creation process
    
    return fig

现在,即使多个用户同时更改他们的主题,他们也不会干扰彼此的图表主题,因为主题是在呈现图表时应用的,并且是特定于用户的.

Django相关问答推荐

在Django的反向函数中添加动态URL

Django Form初始值不在呈现上起作用

如何在Django中将可选参数传递给视图?

将所有守护用户对象权限从一个Django用户重新分配给另一个Django用户

在Python中向函数的查询列表添加条件

Django:添加第二个';详细';用于检索额外信息的视图

如何显示;Django认证系统;在模板中?

在不指定查找的情况下调用 prefetch_lated() 有用吗?

Django ImproperlyConfigured: AUTH_USER_MODEL指向尚未安装的模型'users.User'

在Django测试get方法中获取HttpResponseNotFound

Django rest框架:自定义对象权限不起作用

Django:如何在表单 clean() 方法的 django 验证错误中添加 超链接?

多租户 Django 应用程序:根据请求更改数据库连接?

变量为无时默认模板标签输出的Django设置?

(fields.E300) 字段定义与模型的关系,该模型要么未安装,要么是抽象的

整数的Python正则表达式?

Django ALLOWED_HOSTS IP 范围

如何获取 Django 模型字段对象的值

从 git 存储库中删除并忽略所有具有扩展名的文件

ImportError:没有名为 django_filters 的模块