漏勺:我如何允许无值?

时间:2013-09-12 21:57:33

标签: python colander

说我有一个简单的架构:

class MySchema(colander.MappingSchema):
    thing = colander.SchemaNode(colander.Int())

使用上面的架构,在尝试反序列化{'thing': None}时,我收到错误:

Invalid: {'thing': u'Required'}

看起来漏勺使用None值处理与缺少字段相同的字段。如何解决这个问题并强制执行thing始终提供,但允许它为None

3 个答案:

答案 0 :(得分:4)

请考虑这个解决方案。

import colander


class NoneAcceptantNode(colander.SchemaNode):
    """Accepts None values for schema nodes.
    """

    def deserialize(self, value):
        if value is not None:
            return super(NoneAcceptantNode, self).deserialize(value)


class Person(colander.MappingSchema):
    interest = NoneAcceptantNode(colander.String())


# Passes
print Person().deserialize({'interest': None})

# Passes
print Person().deserialize({'interest': 'kabbalah'})

# Raises an exception
print Person().deserialize({})

答案 1 :(得分:1)

无值将用于反序列化,但是您需要在模式中提供“缺少”参数:

class MySchema(colander.MappingSchema):
    thing = colander.SchemaNode(colander.Int(), missing=None)

http://docs.pylonsproject.org/projects/colander/en/latest/null.html#deserializing-the-null-value

答案 2 :(得分:0)

这是我正在使用的。我将空字符串映射到显式空值。如果required标志为true,则会引发无效错误。

{
   "foo": "",
   "bar": ""
}

此外,在处理查询字符串参数时,foo =,bar =将变为:

public class ThreadSafeContainer<E> {
private Node front;
private Node end;
private int capacity;
private int size;

public ThreadSafeContainer(int capacity) {
    size = 0;
    this.capacity = capacity;
}

public synchronized void add(E item) {
    while (size == capacity) {
        try {
            wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    if (size == 0) {
        notifyAll();
    }

    Node tmp = new Node(item);

    if (end == null) {
        front = tmp;
        end = tmp;
    } else {
        end.next = tmp;
        end = end.next;
    }

    size++;
}

public synchronized E remove() {
    while (size == 0) {
        try {
            wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    if (size == capacity) {
        notifyAll();
    }

    E item = front.item;
    front = front.next;
    size--;
    return item;
}

private class Node {
    E item;
    Node next;

    public Node(E item) {
        this.item = item;
    }
}

只有JSON有效负载才能使用文字空值