将类实例中的数据存储到request.session

时间:2017-08-29 18:18:05

标签: python django

我试图在Django视图之间共享一些数据。我有一个观点,我在那里设置了班级" Mwfrs Buildings"。该类有几个属性,属性和cached_property。

例如:

from django.utils.functional import cached_property

class MwfrsBuildings:

    def __init__(self, form_cleaned_data):
        for key, value in form_cleaned_data.items():
            setattr(self, key, value)

    @property
    def foo(self):
        pass

    @cached_property
    def bar(self):
        pass

我需要从属性和属性中获取数据。我有以下观点:

def buildings(request):
    if request.POST and request.is_ajax():
        s_form = BuildingForm(request.POST)
        if s_form.is_valid():
            method = MwfrsBuildings(s_form.cleaned_data)
            html = render_to_string('wind/results/buildings/buildings_results.html',
                                    {'method': method})
            request.session['building_method'] = method.__dict__
            return JsonResponse({"result": html})
    else:
            return JsonResponse({'building_errors': s_form.errors},
                                status=400)

因为我无法存储实例化的类,所以我使用__dict__方法存储数据。这适用于类属性和cached_property,但不适用于属性。

如何在request.session

中存储类属性

将instanciated类传递给request.session

是可行的

-------------------- UPDATE ----------------------- -

我不知道这是不是一个好习惯,但我想出了使用 Pickle 。例如:

import pickle

def buildings(request):
    if request.POST and request.is_ajax():
        s_form = BuildingForm(request.POST)
        if s_form.is_valid():
            method = MwfrsBuildings(s_form.cleaned_data)
            html = render_to_string('wind/results/buildings/buildings_results.html',
                                    {'method': method})
            with open("building.pickle", "wb") as outfile:
                pickle.dump(method, outfile)
            return JsonResponse({"result": html})
    else:
            return JsonResponse({'building_errors': s_form.errors},
                                status=400)

然后在其他观点中:

def buildings(request):
    # some code
    with open("building.pickle", 'rb') as outfile:
        method = pickle.load(outfile)
    # Then use the instanciated class

__

1 个答案:

答案 0 :(得分:0)

您可以尝试在to_json()课程中创建from_json()MwfrsBuildings实例方法,例如

class MwfrsBuildings(object):
  ...
  def to_json(self):
    data = dict()
    data['my_field'] = self.my_field
    ...
    return json.dumps(data)

  @classmethod
  def from_json(cls, json_data):
    data = json.loads(json_data)
    return cls(my_field=data['my_field'], ...)

然后你可以在你的视图中做这样的事情:

request.session['mydata'] = my_object.to_json()
...
my_object = MwfrsBuildings.from_json(request.session['mydata'])