コード例 #1
0
class KitchenCreateSerializer(ModelSerializer):
    workdays = ListField(child=DictField())
    menu = ListField(child=DictField())

    class Meta:
        model = Kitchen
        fields = "__all__"
コード例 #2
0
class FileSerializer(ModelSerializer):
  name = CharField(max_length=300)
  photo = ImageField(required=False)
  is_public = BooleanField(required=False)
  delete_date = DateField(required=False)
  # read_only
  pk = IntegerField(read_only=True)
  issue_date = DateTimeField(read_only=True)
  update_date = DateTimeField(read_only=True)
  file_user = DictField(read_only=True, source="user_as_dict")
  file_parents = ListField(read_only=True, source="parents_as_list")
  file_children = ListField(read_only=True, source="children_as_list")
  # A `HiddenField` does not take input from the user, or present any output
  fk_user = HiddenField(default=CurrentUserDefault())

  class Meta:
    model = FileModel
    fields = (
      "pk",
      "fk_parent",
      "name",
      "photo",
      "is_public",
      "issue_date",
      "update_date",
      "delete_date",
      "file_user",
      "file_parents",
      "file_children",
      "fk_user",
    )
コード例 #3
0
class DailyPageVisitsSerializer(Serializer):
    day = DateField()
    content_visits = IntegerField()
    communication_visits = IntegerField()
    assessment_visits = IntegerField()
    single_events = ListField()
    submission_events = ListField()
コード例 #4
0
class UserSearchSerializer(ModelSerializer):
    public_email = EmailField(required=False)
    national_code = CharField(required=False, max_length=20, allow_blank=True)
    profile_media = IntegerField(required=False, allow_null=True)
    birth_date = CharField(required=False, max_length=10, allow_blank=True)
    fax = CharField(required=False, allow_blank=True)
    telegram_account = CharField(required=False,
                                 max_length=256,
                                 allow_blank=True)
    description = CharField(required=False, allow_blank=True)
    web_site = ListField(child=URLField(required=False), required=False)
    phone = ListField(child=CharField(max_length=23, required=False),
                      required=False)
    mobile = ListField(child=CharField(max_length=23, required=False),
                       required=False)
    password = CharField(max_length=255)
    auth_mobile = CharField(required=False,
                            validators=[RegexValidator('^[0][9][0-9]{9,9}$')])

    class Meta:
        model = User
        fields = [
            'id', 'username', 'password', 'first_name', 'last_name', 'email',
            'password', 'date_joined', 'web_site', 'public_email',
            'national_code', 'profile_media', 'birth_date', 'fax',
            'telegram_account', 'description', 'phone', 'mobile', 'auth_mobile'
        ]
コード例 #5
0
class RentalPropertySerializer(Serializer):
    # Details
    name = CharField()
    address = CharField()  # Not always available
    latitude = DecimalField(max_digits=10, decimal_places=8)
    longitude = DecimalField(max_digits=11, decimal_places=8)
    offered_by = CharField(allow_null=True)
    description = ListField()

    # Dates
    date_available = DateField()
    post_date = DateTimeField()  # Only applicable for certain websites

    # Costs
    rent_price = DecimalField(max_digits=20, decimal_places=2)
    application_fee = DecimalField(max_digits=10,
                                   decimal_places=2,
                                   allow_null=True)
    security_deposit = DecimalField(max_digits=10,
                                    decimal_places=2,
                                    allow_null=True)

    # Features
    size = DecimalField(max_digits=12, decimal_places=2, allow_null=True)
    bedrooms = IntegerField()
    bathrooms = IntegerField()
    amenities = ListField(
        allow_null=True
    )  # Interrelated with description; text parsing methods?
    tags = ListField()

    # URL Data
    listing_url = CharField()
コード例 #6
0
class SearchSerializer(Serializer):
    """Serializer for search queries."""
    model = ChoiceField([m.label for m in registry.models.values()])
    time = IntegerField(min_value=0, required=False)
    identity = CharField(max_length=256, required=False)
    filters = ListField(child=FilterSerializer(), required=False)
    orders = ListField(child=OrderSerializer(), required=False)

    page = IntegerField(min_value=0, required=False, default=1)
    pagesize = IntegerField(min_value=1, required=False, default=500)
    index = IntegerField(min_value=0, required=False)

    def validate(self, data):
        model_set = set([t[0] for t in registry.path(data['model'])])
        model_set.add(data['model'])

        for f in data.get('filters', []):
            # Make sure filter model is in path of search model
            if f['model'] not in model_set:
                raise ValidationError('Model {} not in path of {}'.format(
                    f['model'], data['model']))

        for o in data.get('orders', []):
            # Make sure order model is in path of search model
            if o['model'] not in model_set:
                raise ValidationError('Model {} not in path of {}'.format(
                    o['model'], data['model']))

        return data
コード例 #7
0
class DataFrameRecordsSerializer(Serializer):
    """
    A Serializer implementation that uses
    :func:`pandas.DataFrame.from_dict <pandas.DataFrame.from_records>` and
    :func:`pandas.DataFrame.to_dict <pandas.DataFrame.to_records>` to convert data to internal
    value and to external representation.
    """
    columns = ListField(child=CharField())
    data = ListField(child=JSONField())

    def to_internal_value(self, data):
        validated_data = super().to_internal_value(data)

        try:
            data_frame = pd.DataFrame.from_records(
                validated_data['data'],
                index='index',
                columns=validated_data['columns'])
            return data_frame
        except ValueError as e:
            raise ValidationError(
                {api_settings.NON_FIELD_ERRORS_KEY: [str(e)]})

    def to_representation(self, instance):
        recarray = instance.to_records(index=True)
        return OrderedDict([('columns', recarray.dtype.names),
                            ('data', recarray.tolist())])
コード例 #8
0
class KitchenSerializer(ModelSerializer):
    user = UserSerializer(many=False, read_only=True)
    workdays = ListField(child=DictField())
    menu = ListField(child=DictField())

    class Meta:
        model = Kitchen
        fields = "__all__"
コード例 #9
0
class SnpSerializer(Serializer):
    dbsnp_ref_genome_build = CharField()
    dbsnp_build = CharField()
    rsid = IntegerField()
    chr_pos = ListField(child=ChrPosSerializer())
    refseq = ListField(child=RefSeqSerializer())
    snp3d = ListField(child=Snp3dSerializer())
    omim = ListField(child=OmimSerializer())
コード例 #10
0
class CuahsiResourceSerializer(ResourceSerializer):
    details_url = CharField()
    sample_mediums = ListField(child=CharField())
    variables = ListField(child=CuahsiVariableSetSerializer())
    service_org = CharField()
    service_code = CharField()
    service_url = CharField()
    service_title = CharField()
    service_citation = CharField()
    begin_date = DateTimeField()
    end_date = DateTimeField()
コード例 #11
0
 def __init__(self):
     super().__init__(
         allow_empty=False, min_length=1, max_length=2,
         child=ListField(
             allow_empty=False, min_length=4, max_length=None,
             child=ListField(
                 child=CoordinateAxisValueField(),
                 allow_empty=False, min_length=2, max_length=2
             )
         )
     )
コード例 #12
0
class USGSResourceSerializer(ResourceSerializer):
    details_url = CharField()
    sample_mediums = ListField(child=CharField())
    variables = ListField(child=USGSVariableSetSerializer())
    service_org = CharField()
    service_orgname = CharField()
    service_code = CharField()
    service_url = CharField()
    monitoring_type = CharField()
    provider_name = CharField()
    service_title = CharField()
    service_citation = CharField()
    begin_date = DateTimeField()
    end_date = DateTimeField()
コード例 #13
0
class UserJwtSerializer(AbstractJwtSerializer):
    user_uuid = UUIDField(source='user_id')
    identity_token = CharField(max_length=40)
    elevated_token = CharField(max_length=40)
    user_permissions = ListField(child=CharField(max_length=120))
    service_permissions = ListField(child=CharField(max_length=120))
    is_loggedin = SerializerMethodField()

    def get_is_user(self, obj):
        return True

    @staticmethod
    def get_is_loggedin(obj):
        return obj.identity_token and obj.elevated_token
コード例 #14
0
class PublishedCompaniesSerializer(Serializer):

    name = CharField(read_only=True)
    number = CharField(read_only=True)
    sectors = ListField(read_only=True)
    employees = CharField(read_only=True)
    keywords = ListField(read_only=True)
    website = CharField(read_only=True)
    facebook_url = CharField(read_only=True)
    linkedin_url = CharField(read_only=True)
    twitter_url = CharField(read_only=True)
    company_email = CharField(read_only=True)
    summary = CharField(read_only=True)
    description = CharField(read_only=True)
コード例 #15
0
ファイル: serializers.py プロジェクト: ebachman/perfectstorm
class GroupSerializer(DocumentSerializer):

    name = CharField(allow_blank=False,
                     allow_null=True,
                     required=False,
                     validators=[UniqueValidator(Group.objects.all())])

    query = EscapedDictField()

    include = ListField(child=CharField(), default=list)
    exclude = ListField(child=CharField(), default=list)

    class Meta:
        model = Group
        fields = ('id', 'name', 'query', 'include', 'exclude', 'services')
コード例 #16
0
class AttackerSerializer(Serializer):
    cords = ListField()
    slowest_unit = ChoiceField([
        'spear', 'sword', 'axe', 'spy', 'light', 'heavy', 'ram', 'catapult',
        'gentry'
    ])
    arrive_time = DateTimeField()
コード例 #17
0
ファイル: serializers.py プロジェクト: czosel/caluma
class SetWorkItemAssignedUsersSerializer(serializers.ModelSerializer):
    work_item = serializers.GlobalIDField(source="id")
    assigned_users = ListField(required=True)

    class Meta:
        model = models.WorkItem
        fields = ("work_item", "assigned_users")
コード例 #18
0
class MenuScreenSerializer(UssdContentBaseSerializer):
    """
    - text:
        .. autoclass:: UssdContentBaseSerializer

    - options:
        This is a list of options to display to the user
        each option is
            .. autoclass:: MenuOptionSerializer

    - items:
        Sometimes you what to display a list of items and not
        menu options. Item is used for this
            .. autoclass:: ItemsSerializer

    - error_message: This is an optional message to display if the
                     user enters invalid input

    - option and items are mutual exclusive.

    Examples of menu screen:

        .. literalinclude:: .././ussd/tests/sample_screen_definition/valid_menu_screen_conf.yml
    """
    options = ListField(child=MenuOptionSerializer(), required=False)
    items = ItemsSerializer(required=False)

    def validate(self, data):
        if 'options' not in data and 'items' not in data:
            raise ValidationError(
                'options field is required or items is required')
        return super(MenuScreenSerializer, self).validate(data)
コード例 #19
0
class OaiProviderSetSerializer(DocumentSerializer):
    templates_manager = ListField(child=CharField(), required=True)

    class Meta(object):
        model = OaiProviderSet
        fields = [
            "id", "set_spec", "set_name", "description", "templates_manager"
        ]
        depth = 1

        read_only_fields = ("id", )

    def create(self, validated_data):
        return oai_provider_set_api.upsert(OaiProviderSet(**validated_data))

    def update(self, instance, validated_data):
        instance.set_spec = validated_data.get("set_spec", instance.set_spec)
        instance.set_name = validated_data.get("set_name", instance.set_name)
        templates_manager = validated_data.get("templates_manager", [])
        if len(templates_manager) > 0:
            templates_manager = [
                version_manager_api.get(id_, request=self.context["request"])
                for id_ in templates_manager
            ]
            instance.templates_manager = templates_manager
        instance.description = validated_data.get("description",
                                                  instance.description)
        return oai_provider_set_api.upsert(instance)
コード例 #20
0
class SongArtistsListSerializer(Serializer):
    '''
    A serializer for adding or removing artists from a song based on
    the song's id number.
    '''
    # TODO: Probably should move to PrimaryKeyRelatedField.
    artists = ListField(child=IntegerField(), min_length=1, max_length=10)
コード例 #21
0
class OaiProviderSetSerializer(DocumentSerializer):
    templates_manager = ListField(child=CharField(), required=True)

    class Meta:
        model = OaiProviderSet
        fields = [
            'id', 'set_spec', 'set_name', 'description', 'templates_manager'
        ]
        depth = 1

        read_only_fields = ('id', )

    def create(self, validated_data):
        return oai_provider_set_api.upsert(OaiProviderSet(**validated_data))

    def update(self, instance, validated_data):
        instance.set_spec = validated_data.get('set_spec', instance.set_spec)
        instance.set_name = validated_data.get('set_name', instance.set_name)
        templates_manager = validated_data.get('templates_manager', [])
        if len(templates_manager) > 0:
            templates_manager = [
                version_manager_api.get(id_) for id_ in templates_manager
            ]
            instance.templates_manager = templates_manager
        instance.description = validated_data.get('description',
                                                  instance.description)
        return oai_provider_set_api.upsert(instance)
コード例 #22
0
class PickupUpdateRequest(Serializer):

    date = CharField(required=True, help_text="The expected pickup date")
    address = Address(required=True, help_text="The pickup address")
    parcels = ListField(child=Parcel(),
                        required=False,
                        help_text="The shipment parcels to pickup.")

    confirmation_number = CharField(required=True,
                                    help_text="pickup identification number")

    ready_time = CharField(required=True,
                           help_text="The ready time for pickup.")
    closing_time = CharField(
        required=True, help_text="The closing or late time of the pickup")
    instruction = CharField(required=False,
                            help_text="""
    The pickup instruction.
    
    eg: Handle with care.
    """)
    package_location = CharField(required=False,
                                 help_text="""
    The package(s) location.
    
    eg: Behind the entrance door.
    """)
コード例 #23
0
def process_field(field, required=False, read_only=False, allow_null=False):
    """
    Used to process a thrift data type field
    :param field:
    :param required:
    :param read_only:
    :param allow_null:
    :return:
    """
    if field[1] in mapping:
        # handling scenarios when the thrift field type is present in the
        # mapping
        field_class = mapping[field[1]]
        kwargs = dict(required=required, read_only=read_only)
        # allow_null isn't allowed for BooleanField
        if field_class not in (BooleanField, ):
            kwargs['allow_null'] = allow_null
        # allow_null CharField are also allowed to be blank
        if field_class == CharField:
            kwargs['allow_blank'] = allow_null
        return mapping[field[1]](**kwargs)
    elif field[1] == TType.LIST:
        # handling scenario when the thrift field type is list
        list_field_serializer = process_list_field(field)
        return ListField(child=list_field_serializer,
                         required=required,
                         read_only=read_only,
                         allow_null=allow_null)
    elif field[1] == TType.STRUCT:
        # handling scenario when the thrift field type is struct
        return create_serializer(field[3][0],
                                 required=required,
                                 read_only=read_only,
                                 allow_null=allow_null)
コード例 #24
0
class WeeklyPageVisitsSerializer(Serializer):
    day = DateField()
    content_visits = IntegerField()
    communication_visits = IntegerField()
    assessment_visits = IntegerField()
    unique_visits = IntegerField()
    repeating_events = ListField()
コード例 #25
0
class ContactInfoSerializer(Serializer):
    given_name = CharField(required=False)
    givenName = CharField(source='given_name', required=False)

    full_name = CharField(required=False)
    fullName = CharField(source='full_name', required=False)

    family_name = CharField(required=False)
    familyName = CharField(source='family_name', required=False)

    websites = ListField(child=CharField(max_length=200, allow_blank=True))

    def to_representation(self, obj):
        return {
            'givenName': obj.given_name,
            'fullName': obj.full_name,
            'familyName': obj.family_name,
            'websites': obj.websites,
        }

    class Meta:
        model = ContactInfo
        fields = (
            'given_name',
            'givenName',
            'full_name',
            'fullName',
            'family_name',
            'familyName',
            'websites',
        )
コード例 #26
0
class CommandSerializer(ModelSerializer):
    cycle_duration = IntegerField(
        default=settings.DEFAULT_RANDOM_WORD_CYCLE_DURATION)
    words = ListField(child=CharField(), write_only=True)

    class Meta:
        model = Command
        fields = '__all__'
        read_only_fields = (
            'id',
            'creation_time',
        )

    def create(self, validated_data):
        words = validated_data.pop('words')
        instance = super().create(validated_data)

        word_ids = []
        for word in words:
            word_ids.append(
                Word.objects.create(value=word, command=instance).id)

        random.shuffle(word_ids)
        for word_id in word_ids:
            process_word.apply_async((word_id, ))

        return instance

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        representation['words'] = WordSerializer(instance.words.all(),
                                                 many=True).data
        return representation
コード例 #27
0
class RateResponse(Serializer):
    messages = ListField(
        child=Message(),
        required=False,
        help_text="The list of note, error or warning messages")
    shipment = ShipmentRate(required=False,
                            help_text="The newly rated shipment")
コード例 #28
0
class RateDetails(Serializer):

    id = UUIDField(required=False, help_text="A unique rate identifier")
    carrier_name = CharField(required=True, help_text="The rate's carrier")
    carrier_id = CharField(
        required=True,
        help_text="The targeted carrier's name (unique identifier)")
    currency = CharField(required=True,
                         help_text="The rate monetary values currency code")
    service = CharField(required=False,
                        help_text="The carrier's rate (quote) service")
    discount = FloatField(
        required=False,
        help_text="The monetary amount of the discount on the rate")
    base_charge = FloatField(default=0.0,
                             help_text="""
    The rate's monetary amount of the base charge.
    
    This is the net amount of the rate before additional charges
    """)
    total_charge = FloatField(default=0.0,
                              help_text="""
    The rate's monetary amount of the total charge.
    
    This is the gross amount of the rate after adding the additional charges
    """)
    duties_and_taxes = FloatField(
        required=False,
        help_text="The monetary amount of the duties and taxes if applied")
    estimated_delivery = CharField(required=False,
                                   help_text="The estimated delivery date")
    extra_charges = ListField(
        child=ChargeDetails(),
        required=False,
        help_text="list of the rate's additional charges")
コード例 #29
0
class CreatePollPostSerializer(ModelSerializer, CreatePostCommonFields):

    ques = CharField(allow_blank=True,
                     error_messages={
                         'required': 'ques key is required',
                         'blank': 'ques field is required'
                     })
    poll_end_value = CharField(
        error_messages={
            'required': 'poll_end_value key is required',
            'blank': 'poll_end_value is required'
        })
    poll_end_type = ChoiceField(choices=PollPost.POLL_END_TYPE,
                                error_messages={
                                    'required':
                                    'poll_end_type key is required',
                                    'blank': 'poll_end_type is required'
                                })
    text_options = ListField(
        allow_empty=True,
        required=False,
        error_messages={'required': 'text_options key is required'})
    image_options = ImageField(
        required=False,
        max_length=None,
        allow_empty_file=True,
        error_messages={'required': 'image_options key is required'})

    class Meta:
        model = PollPost
        fields = [
            'about', 'description', 'is_18_plus', 'ques', 'poll_end_value',
            'poll_end_type', 'text_options', 'image_options'
        ]
コード例 #30
0
class FacilityQueryParamsSerializer(Serializer):
    name = CharField(required=False)
    contributors = ListField(
        child=IntegerField(required=False),
        required=False,
    )
    contributor_types = ListField(
        child=CharField(required=False),
        required=False,
    )
    countries = ListField(
        child=CharField(required=False),
        required=False,
    )
    page = IntegerField(required=False)
    pageSize = IntegerField(required=False)