- Хроники. - -

AppEngine сохраняем перечисление в базу

Posted By Ikutsin On 4 апреля 2010 @ 0:04 In Python | Comments Disabled

Продолжаю работать с AppEngine. Столкнулся с мыслью, что использование целого числа для статуса не очень удобно. Я привык к C# и конструкции языка, типа Enum. По этому, решил найти нечто подобное для GAE. Идея в том, чтобы использовать следующий синтаксис:

status = validators.EnumProperty(choice=['not_moderated','moderated','blocked'])

Класс для поля перечеслиения [1] выглядит так:

from google.appengine.ext import db

class EnumProperty(db.Property):
    """
    Maps a list of strings to be saved as int. The property is set or get using
    the string value, but it is stored using its index in the 'choices' list.
    """
    data_type = int

    def __init__(self, choices=None, **kwargs):
        if not isinstance(choices, list):
            raise TypeError('Choices must be a list.')
        super(EnumProperty, self).__init__(choices=choices, **kwargs)

    def get_value_for_datastore(self, model_instance):
        value = self.__get__(model_instance, model_instance.__class__)
        if value is not None:
            return int(self.choices.index(value))

    def make_value_from_datastore(self, value):
        if value is not None:
            return self.choices[int(value)]

    def empty(self, value):
        return value is None

Article printed from Хроники.:

URL to article: /1391-appengine-soxranyaem-perechislenie-v-bazu

URLs in this post:

[1] поля перечеслиения: http://appengine-cookbook.appspot.com/recipe/enumproperty/

Copyright © 2008 Все, что меня окружает. All rights reserved.