We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
_since overflow error: long too big to convert
When since is too big with the Postgresql backend it fails with an OverflowError: https://sentry.prod.mozaws.net/operations/kinto-prod-1/issues/382250/

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `kinto/core/resource/schema.py`
Content:
```
1 import warnings
2 
3 import colander
4 
5 from kinto.core.schema import (Any, HeaderField, QueryField, HeaderQuotedInteger,
6                                FieldList, TimeStamp, URL)
7 from kinto.core.utils import native_value
8 
9 
10 class TimeStamp(TimeStamp):
11     """This schema is deprecated, you shoud use `kinto.core.schema.TimeStamp` instead."""
12 
13     def __init__(self, *args, **kwargs):
14         message = ("`kinto.core.resource.schema.TimeStamp` is deprecated, "
15                    "use `kinto.core.schema.TimeStamp` instead.")
16         warnings.warn(message, DeprecationWarning)
17         super(TimeStamp, self).__init__(*args, **kwargs)
18 
19 
20 class URL(URL):
21     """This schema is deprecated, you shoud use `kinto.core.schema.URL` instead."""
22 
23     def __init__(self, *args, **kwargs):
24         message = ("`kinto.core.resource.schema.URL` is deprecated, "
25                    "use `kinto.core.schema.URL` instead.")
26         warnings.warn(message, DeprecationWarning)
27         super(URL, self).__init__(*args, **kwargs)
28 
29 
30 # Resource related schemas
31 
32 
33 class ResourceSchema(colander.MappingSchema):
34     """Base resource schema, with *Cliquet* specific built-in options."""
35 
36     class Options:
37         """
38         Resource schema options.
39 
40         This is meant to be overriden for changing values:
41 
42         .. code-block:: python
43 
44             class Product(ResourceSchema):
45                 reference = colander.SchemaNode(colander.String())
46 
47                 class Options:
48                     readonly_fields = ('reference',)
49         """
50         readonly_fields = tuple()
51         """Fields that cannot be updated. Values for fields will have to be
52         provided either during record creation, through default values using
53         ``missing`` attribute or implementing a custom logic in
54         :meth:`kinto.core.resource.UserResource.process_record`.
55         """
56 
57         preserve_unknown = True
58         """Define if unknown fields should be preserved or not.
59 
60         The resource is schema-less by default. In other words, any field name
61         will be accepted on records. Set this to ``False`` in order to limit
62         the accepted fields to the ones defined in the schema.
63         """
64 
65     @classmethod
66     def get_option(cls, attr):
67         default_value = getattr(ResourceSchema.Options, attr)
68         return getattr(cls.Options, attr,  default_value)
69 
70     @classmethod
71     def is_readonly(cls, field):
72         """Return True if specified field name is read-only.
73 
74         :param str field: the field name in the schema
75         :returns: ``True`` if the specified field is read-only,
76             ``False`` otherwise.
77         :rtype: bool
78         """
79         return field in cls.get_option("readonly_fields")
80 
81     def schema_type(self):
82         if self.get_option("preserve_unknown") is True:
83             unknown = 'preserve'
84         else:
85             unknown = 'ignore'
86         return colander.Mapping(unknown=unknown)
87 
88 
89 class PermissionsSchema(colander.SchemaNode):
90     """A permission mapping defines ACEs.
91 
92     It has permission names as keys and principals as values.
93 
94     ::
95 
96         {
97             "write": ["fxa:af3e077eb9f5444a949ad65aa86e82ff"],
98             "groups:create": ["fxa:70a9335eecfe440fa445ba752a750f3d"]
99         }
100 
101     """
102 
103     def __init__(self, *args, **kwargs):
104         self.known_perms = kwargs.pop('permissions', tuple())
105         super(PermissionsSchema, self).__init__(*args, **kwargs)
106 
107         for perm in self.known_perms:
108             self[perm] = self._get_node_principals(perm)
109 
110     def schema_type(self):
111         if self.known_perms:
112             return colander.Mapping(unknown='raise')
113         else:
114             return colander.Mapping(unknown='preserve')
115 
116     def deserialize(self, cstruct=colander.null):
117 
118         # If permissions are not a mapping (e.g null or invalid), try deserializing
119         if not isinstance(cstruct, dict):
120             return super(PermissionsSchema, self).deserialize(cstruct)
121 
122         # If permissions are listed, check fields and produce fancy error messages
123         if self.known_perms:
124             for perm in cstruct:
125                 colander.OneOf(choices=self.known_perms)(self, perm)
126             return super(PermissionsSchema, self).deserialize(cstruct)
127 
128         # Else deserialize the fields that are not on the schema
129         permissions = {}
130         perm_schema = colander.SequenceSchema(colander.SchemaNode(colander.String()))
131         for perm, principals in cstruct.items():
132             permissions[perm] = perm_schema.deserialize(principals)
133 
134         return permissions
135 
136     def _get_node_principals(self, perm):
137         principal = colander.SchemaNode(colander.String())
138         return colander.SchemaNode(colander.Sequence(), principal, name=perm,
139                                    missing=colander.drop)
140 
141 
142 # Header schemas
143 
144 
145 class HeaderSchema(colander.MappingSchema):
146     """Base schema used for validating and deserializing request headers. """
147 
148     missing = colander.drop
149 
150     if_match = HeaderQuotedInteger(name='If-Match')
151     if_none_match = HeaderQuotedInteger(name='If-None-Match')
152 
153     @staticmethod
154     def schema_type():
155         return colander.Mapping(unknown='preserve')
156 
157 
158 class PatchHeaderSchema(HeaderSchema):
159     """Header schema used with PATCH requests."""
160 
161     def response_behavior_validator():
162         return colander.OneOf(['full', 'light', 'diff'])
163 
164     response_behaviour = HeaderField(colander.String(), name='Response-Behavior',
165                                      validator=response_behavior_validator())
166 
167 
168 # Querystring schemas
169 
170 
171 class QuerySchema(colander.MappingSchema):
172     """
173     Schema used for validating and deserializing querystrings. It will include
174     and try to guess the type of unknown fields (field filters) on deserialization.
175     """
176     missing = colander.drop
177 
178     @staticmethod
179     def schema_type():
180         return colander.Mapping(unknown='ignore')
181 
182     def deserialize(self, cstruct=colander.null):
183         """
184         Deserialize and validate the QuerySchema fields and try to deserialize and
185         get the native value of additional filds (field filters) that may be present
186         on the cstruct.
187 
188         e.g:: ?exclude_id=a,b&deleted=true -> {'exclude_id': ['a', 'b'], deleted: True}
189         """
190         values = {}
191 
192         schema_values = super(QuerySchema, self).deserialize(cstruct)
193         if schema_values is colander.drop:
194             return schema_values
195 
196         # Deserialize querystring field filters (see docstring e.g)
197         for k, v in cstruct.items():
198             # Deserialize lists used on in_ and exclude_ filters
199             if k.startswith('in_') or k.startswith('exclude_'):
200                 as_list = FieldList().deserialize(v)
201                 if isinstance(as_list, list):
202                     values[k] = [native_value(v) for v in as_list]
203             else:
204                 values[k] = native_value(v)
205 
206         values.update(schema_values)
207         return values
208 
209 
210 class CollectionQuerySchema(QuerySchema):
211     """Querystring schema used with collections."""
212 
213     _limit = QueryField(colander.Integer())
214     _sort = FieldList()
215     _token = QueryField(colander.String())
216     _since = QueryField(colander.Integer())
217     _to = QueryField(colander.Integer())
218     _before = QueryField(colander.Integer())
219     id = QueryField(colander.String())
220     last_modified = QueryField(colander.Integer())
221 
222 
223 class RecordGetQuerySchema(QuerySchema):
224     """Querystring schema for GET record requests."""
225 
226     _fields = FieldList()
227 
228 
229 class CollectionGetQuerySchema(CollectionQuerySchema):
230     """Querystring schema for GET collection requests."""
231 
232     _fields = FieldList()
233 
234 
235 # Body Schemas
236 
237 
238 class RecordSchema(colander.MappingSchema):
239 
240     @colander.deferred
241     def data(node, kwargs):
242         data = kwargs.get('data')
243         if data:
244             # Check if empty record is allowed.
245             # (e.g every schema fields have defaults)
246             try:
247                 data.deserialize({})
248             except colander.Invalid:
249                 pass
250             else:
251                 data.default = {}
252                 data.missing = colander.drop
253         return data
254 
255     @colander.deferred
256     def permissions(node, kwargs):
257         def get_perms(node, kwargs):
258             return kwargs.get('permissions')
259         # Set if node is provided, else keep deferred. This allows binding the body
260         # on Resource first and bind permissions later if using SharableResource.
261         return get_perms(node, kwargs) or colander.deferred(get_perms)
262 
263     @staticmethod
264     def schema_type():
265         return colander.Mapping(unknown='raise')
266 
267 
268 class JsonPatchOperationSchema(colander.MappingSchema):
269     """Single JSON Patch Operation."""
270 
271     def op_validator():
272         op_values = ['test', 'add', 'remove', 'replace', 'move', 'copy']
273         return colander.OneOf(op_values)
274 
275     def path_validator():
276         return colander.Regex('(/\w*)+')
277 
278     op = colander.SchemaNode(colander.String(), validator=op_validator())
279     path = colander.SchemaNode(colander.String(), validator=path_validator())
280     from_ = colander.SchemaNode(colander.String(), name='from',
281                                 validator=path_validator(), missing=colander.drop)
282     value = colander.SchemaNode(Any(), missing=colander.drop)
283 
284     @staticmethod
285     def schema_type():
286         return colander.Mapping(unknown='raise')
287 
288 
289 class JsonPatchBodySchema(colander.SequenceSchema):
290     """Body used with JSON Patch (application/json-patch+json) as in RFC 6902."""
291 
292     operations = JsonPatchOperationSchema(missing=colander.drop)
293 
294 
295 # Request schemas
296 
297 
298 class RequestSchema(colander.MappingSchema):
299     """Base schema for kinto requests."""
300 
301     @colander.deferred
302     def header(node, kwargs):
303         return kwargs.get('header')
304 
305     @colander.deferred
306     def querystring(node, kwargs):
307         return kwargs.get('querystring')
308 
309     def after_bind(self, node, kw):
310         # Set default bindings
311         if not self.get('header'):
312             self['header'] = HeaderSchema()
313         if not self.get('querystring'):
314             self['querystring'] = QuerySchema()
315 
316 
317 class PayloadRequestSchema(RequestSchema):
318     """Base schema for methods that use a JSON request body."""
319 
320     @colander.deferred
321     def body(node, kwargs):
322         def get_body(node, kwargs):
323             return kwargs.get('body')
324         # Set if node is provided, else keep deferred (and allow bindind later)
325         return get_body(node, kwargs) or colander.deferred(get_body)
326 
327 
328 class JsonPatchRequestSchema(RequestSchema):
329     """JSON Patch (application/json-patch+json) request schema."""
330 
331     body = JsonPatchBodySchema()
332     querystring = QuerySchema()
333     header = PatchHeaderSchema()
334
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/kinto/core/resource/schema.py b/kinto/core/resource/schema.py
--- a/kinto/core/resource/schema.py
+++ b/kinto/core/resource/schema.py
@@ -1,3 +1,4 @@
+from __future__ import division
 import warnings
 
 import colander
@@ -6,6 +7,10 @@
                                FieldList, TimeStamp, URL)
 from kinto.core.utils import native_value
 
+POSTGRESQL_MAX_INTEGER_VALUE = 2**64 // 2
+
+positive_big_integer = colander.Range(min=0, max=POSTGRESQL_MAX_INTEGER_VALUE)
+
 
 class TimeStamp(TimeStamp):
     """This schema is deprecated, you shoud use `kinto.core.schema.TimeStamp` instead."""
@@ -210,14 +215,14 @@
 class CollectionQuerySchema(QuerySchema):
     """Querystring schema used with collections."""
 
-    _limit = QueryField(colander.Integer())
+    _limit = QueryField(colander.Integer(), validator=positive_big_integer)
     _sort = FieldList()
     _token = QueryField(colander.String())
-    _since = QueryField(colander.Integer())
-    _to = QueryField(colander.Integer())
-    _before = QueryField(colander.Integer())
+    _since = QueryField(colander.Integer(), validator=positive_big_integer)
+    _to = QueryField(colander.Integer(), validator=positive_big_integer)
+    _before = QueryField(colander.Integer(), validator=positive_big_integer)
     id = QueryField(colander.String())
-    last_modified = QueryField(colander.Integer())
+    last_modified = QueryField(colander.Integer(), validator=positive_big_integer)
 
 
 class RecordGetQuerySchema(QuerySchema):

{"golden_diff": "diff --git a/kinto/core/resource/schema.py b/kinto/core/resource/schema.py\n--- a/kinto/core/resource/schema.py\n+++ b/kinto/core/resource/schema.py\n@@ -1,3 +1,4 @@\n+from __future__ import division\n import warnings\n \n import colander\n@@ -6,6 +7,10 @@\n                                FieldList, TimeStamp, URL)\n from kinto.core.utils import native_value\n \n+POSTGRESQL_MAX_INTEGER_VALUE = 2**64 // 2\n+\n+positive_big_integer = colander.Range(min=0, max=POSTGRESQL_MAX_INTEGER_VALUE)\n+\n \n class TimeStamp(TimeStamp):\n     \"\"\"This schema is deprecated, you shoud use `kinto.core.schema.TimeStamp` instead.\"\"\"\n@@ -210,14 +215,14 @@\n class CollectionQuerySchema(QuerySchema):\n     \"\"\"Querystring schema used with collections.\"\"\"\n \n-    _limit = QueryField(colander.Integer())\n+    _limit = QueryField(colander.Integer(), validator=positive_big_integer)\n     _sort = FieldList()\n     _token = QueryField(colander.String())\n-    _since = QueryField(colander.Integer())\n-    _to = QueryField(colander.Integer())\n-    _before = QueryField(colander.Integer())\n+    _since = QueryField(colander.Integer(), validator=positive_big_integer)\n+    _to = QueryField(colander.Integer(), validator=positive_big_integer)\n+    _before = QueryField(colander.Integer(), validator=positive_big_integer)\n     id = QueryField(colander.String())\n-    last_modified = QueryField(colander.Integer())\n+    last_modified = QueryField(colander.Integer(), validator=positive_big_integer)\n \n \n class RecordGetQuerySchema(QuerySchema):\n", "issue": "_since overflow error: long too big to convert\nWhen since is too big with the Postgresql backend it fails with an OverflowError: https://sentry.prod.mozaws.net/operations/kinto-prod-1/issues/382250/\n", "before_files": [{"content": "import warnings\n\nimport colander\n\nfrom kinto.core.schema import (Any, HeaderField, QueryField, HeaderQuotedInteger,\n                               FieldList, TimeStamp, URL)\nfrom kinto.core.utils import native_value\n\n\nclass TimeStamp(TimeStamp):\n    \"\"\"This schema is deprecated, you shoud use `kinto.core.schema.TimeStamp` instead.\"\"\"\n\n    def __init__(self, *args, **kwargs):\n        message = (\"`kinto.core.resource.schema.TimeStamp` is deprecated, \"\n                   \"use `kinto.core.schema.TimeStamp` instead.\")\n        warnings.warn(message, DeprecationWarning)\n        super(TimeStamp, self).__init__(*args, **kwargs)\n\n\nclass URL(URL):\n    \"\"\"This schema is deprecated, you shoud use `kinto.core.schema.URL` instead.\"\"\"\n\n    def __init__(self, *args, **kwargs):\n        message = (\"`kinto.core.resource.schema.URL` is deprecated, \"\n                   \"use `kinto.core.schema.URL` instead.\")\n        warnings.warn(message, DeprecationWarning)\n        super(URL, self).__init__(*args, **kwargs)\n\n\n# Resource related schemas\n\n\nclass ResourceSchema(colander.MappingSchema):\n    \"\"\"Base resource schema, with *Cliquet* specific built-in options.\"\"\"\n\n    class Options:\n        \"\"\"\n        Resource schema options.\n\n        This is meant to be overriden for changing values:\n\n        .. code-block:: python\n\n            class Product(ResourceSchema):\n                reference = colander.SchemaNode(colander.String())\n\n                class Options:\n                    readonly_fields = ('reference',)\n        \"\"\"\n        readonly_fields = tuple()\n        \"\"\"Fields that cannot be updated. Values for fields will have to be\n        provided either during record creation, through default values using\n        ``missing`` attribute or implementing a custom logic in\n        :meth:`kinto.core.resource.UserResource.process_record`.\n        \"\"\"\n\n        preserve_unknown = True\n        \"\"\"Define if unknown fields should be preserved or not.\n\n        The resource is schema-less by default. In other words, any field name\n        will be accepted on records. Set this to ``False`` in order to limit\n        the accepted fields to the ones defined in the schema.\n        \"\"\"\n\n    @classmethod\n    def get_option(cls, attr):\n        default_value = getattr(ResourceSchema.Options, attr)\n        return getattr(cls.Options, attr,  default_value)\n\n    @classmethod\n    def is_readonly(cls, field):\n        \"\"\"Return True if specified field name is read-only.\n\n        :param str field: the field name in the schema\n        :returns: ``True`` if the specified field is read-only,\n            ``False`` otherwise.\n        :rtype: bool\n        \"\"\"\n        return field in cls.get_option(\"readonly_fields\")\n\n    def schema_type(self):\n        if self.get_option(\"preserve_unknown\") is True:\n            unknown = 'preserve'\n        else:\n            unknown = 'ignore'\n        return colander.Mapping(unknown=unknown)\n\n\nclass PermissionsSchema(colander.SchemaNode):\n    \"\"\"A permission mapping defines ACEs.\n\n    It has permission names as keys and principals as values.\n\n    ::\n\n        {\n            \"write\": [\"fxa:af3e077eb9f5444a949ad65aa86e82ff\"],\n            \"groups:create\": [\"fxa:70a9335eecfe440fa445ba752a750f3d\"]\n        }\n\n    \"\"\"\n\n    def __init__(self, *args, **kwargs):\n        self.known_perms = kwargs.pop('permissions', tuple())\n        super(PermissionsSchema, self).__init__(*args, **kwargs)\n\n        for perm in self.known_perms:\n            self[perm] = self._get_node_principals(perm)\n\n    def schema_type(self):\n        if self.known_perms:\n            return colander.Mapping(unknown='raise')\n        else:\n            return colander.Mapping(unknown='preserve')\n\n    def deserialize(self, cstruct=colander.null):\n\n        # If permissions are not a mapping (e.g null or invalid), try deserializing\n        if not isinstance(cstruct, dict):\n            return super(PermissionsSchema, self).deserialize(cstruct)\n\n        # If permissions are listed, check fields and produce fancy error messages\n        if self.known_perms:\n            for perm in cstruct:\n                colander.OneOf(choices=self.known_perms)(self, perm)\n            return super(PermissionsSchema, self).deserialize(cstruct)\n\n        # Else deserialize the fields that are not on the schema\n        permissions = {}\n        perm_schema = colander.SequenceSchema(colander.SchemaNode(colander.String()))\n        for perm, principals in cstruct.items():\n            permissions[perm] = perm_schema.deserialize(principals)\n\n        return permissions\n\n    def _get_node_principals(self, perm):\n        principal = colander.SchemaNode(colander.String())\n        return colander.SchemaNode(colander.Sequence(), principal, name=perm,\n                                   missing=colander.drop)\n\n\n# Header schemas\n\n\nclass HeaderSchema(colander.MappingSchema):\n    \"\"\"Base schema used for validating and deserializing request headers. \"\"\"\n\n    missing = colander.drop\n\n    if_match = HeaderQuotedInteger(name='If-Match')\n    if_none_match = HeaderQuotedInteger(name='If-None-Match')\n\n    @staticmethod\n    def schema_type():\n        return colander.Mapping(unknown='preserve')\n\n\nclass PatchHeaderSchema(HeaderSchema):\n    \"\"\"Header schema used with PATCH requests.\"\"\"\n\n    def response_behavior_validator():\n        return colander.OneOf(['full', 'light', 'diff'])\n\n    response_behaviour = HeaderField(colander.String(), name='Response-Behavior',\n                                     validator=response_behavior_validator())\n\n\n# Querystring schemas\n\n\nclass QuerySchema(colander.MappingSchema):\n    \"\"\"\n    Schema used for validating and deserializing querystrings. It will include\n    and try to guess the type of unknown fields (field filters) on deserialization.\n    \"\"\"\n    missing = colander.drop\n\n    @staticmethod\n    def schema_type():\n        return colander.Mapping(unknown='ignore')\n\n    def deserialize(self, cstruct=colander.null):\n        \"\"\"\n        Deserialize and validate the QuerySchema fields and try to deserialize and\n        get the native value of additional filds (field filters) that may be present\n        on the cstruct.\n\n        e.g:: ?exclude_id=a,b&deleted=true -> {'exclude_id': ['a', 'b'], deleted: True}\n        \"\"\"\n        values = {}\n\n        schema_values = super(QuerySchema, self).deserialize(cstruct)\n        if schema_values is colander.drop:\n            return schema_values\n\n        # Deserialize querystring field filters (see docstring e.g)\n        for k, v in cstruct.items():\n            # Deserialize lists used on in_ and exclude_ filters\n            if k.startswith('in_') or k.startswith('exclude_'):\n                as_list = FieldList().deserialize(v)\n                if isinstance(as_list, list):\n                    values[k] = [native_value(v) for v in as_list]\n            else:\n                values[k] = native_value(v)\n\n        values.update(schema_values)\n        return values\n\n\nclass CollectionQuerySchema(QuerySchema):\n    \"\"\"Querystring schema used with collections.\"\"\"\n\n    _limit = QueryField(colander.Integer())\n    _sort = FieldList()\n    _token = QueryField(colander.String())\n    _since = QueryField(colander.Integer())\n    _to = QueryField(colander.Integer())\n    _before = QueryField(colander.Integer())\n    id = QueryField(colander.String())\n    last_modified = QueryField(colander.Integer())\n\n\nclass RecordGetQuerySchema(QuerySchema):\n    \"\"\"Querystring schema for GET record requests.\"\"\"\n\n    _fields = FieldList()\n\n\nclass CollectionGetQuerySchema(CollectionQuerySchema):\n    \"\"\"Querystring schema for GET collection requests.\"\"\"\n\n    _fields = FieldList()\n\n\n# Body Schemas\n\n\nclass RecordSchema(colander.MappingSchema):\n\n    @colander.deferred\n    def data(node, kwargs):\n        data = kwargs.get('data')\n        if data:\n            # Check if empty record is allowed.\n            # (e.g every schema fields have defaults)\n            try:\n                data.deserialize({})\n            except colander.Invalid:\n                pass\n            else:\n                data.default = {}\n                data.missing = colander.drop\n        return data\n\n    @colander.deferred\n    def permissions(node, kwargs):\n        def get_perms(node, kwargs):\n            return kwargs.get('permissions')\n        # Set if node is provided, else keep deferred. This allows binding the body\n        # on Resource first and bind permissions later if using SharableResource.\n        return get_perms(node, kwargs) or colander.deferred(get_perms)\n\n    @staticmethod\n    def schema_type():\n        return colander.Mapping(unknown='raise')\n\n\nclass JsonPatchOperationSchema(colander.MappingSchema):\n    \"\"\"Single JSON Patch Operation.\"\"\"\n\n    def op_validator():\n        op_values = ['test', 'add', 'remove', 'replace', 'move', 'copy']\n        return colander.OneOf(op_values)\n\n    def path_validator():\n        return colander.Regex('(/\\w*)+')\n\n    op = colander.SchemaNode(colander.String(), validator=op_validator())\n    path = colander.SchemaNode(colander.String(), validator=path_validator())\n    from_ = colander.SchemaNode(colander.String(), name='from',\n                                validator=path_validator(), missing=colander.drop)\n    value = colander.SchemaNode(Any(), missing=colander.drop)\n\n    @staticmethod\n    def schema_type():\n        return colander.Mapping(unknown='raise')\n\n\nclass JsonPatchBodySchema(colander.SequenceSchema):\n    \"\"\"Body used with JSON Patch (application/json-patch+json) as in RFC 6902.\"\"\"\n\n    operations = JsonPatchOperationSchema(missing=colander.drop)\n\n\n# Request schemas\n\n\nclass RequestSchema(colander.MappingSchema):\n    \"\"\"Base schema for kinto requests.\"\"\"\n\n    @colander.deferred\n    def header(node, kwargs):\n        return kwargs.get('header')\n\n    @colander.deferred\n    def querystring(node, kwargs):\n        return kwargs.get('querystring')\n\n    def after_bind(self, node, kw):\n        # Set default bindings\n        if not self.get('header'):\n            self['header'] = HeaderSchema()\n        if not self.get('querystring'):\n            self['querystring'] = QuerySchema()\n\n\nclass PayloadRequestSchema(RequestSchema):\n    \"\"\"Base schema for methods that use a JSON request body.\"\"\"\n\n    @colander.deferred\n    def body(node, kwargs):\n        def get_body(node, kwargs):\n            return kwargs.get('body')\n        # Set if node is provided, else keep deferred (and allow bindind later)\n        return get_body(node, kwargs) or colander.deferred(get_body)\n\n\nclass JsonPatchRequestSchema(RequestSchema):\n    \"\"\"JSON Patch (application/json-patch+json) request schema.\"\"\"\n\n    body = JsonPatchBodySchema()\n    querystring = QuerySchema()\n    header = PatchHeaderSchema()\n", "path": "kinto/core/resource/schema.py"}], "after_files": [{"content": "from __future__ import division\nimport warnings\n\nimport colander\n\nfrom kinto.core.schema import (Any, HeaderField, QueryField, HeaderQuotedInteger,\n                               FieldList, TimeStamp, URL)\nfrom kinto.core.utils import native_value\n\nPOSTGRESQL_MAX_INTEGER_VALUE = 2**64 // 2\n\npositive_big_integer = colander.Range(min=0, max=POSTGRESQL_MAX_INTEGER_VALUE)\n\n\nclass TimeStamp(TimeStamp):\n    \"\"\"This schema is deprecated, you shoud use `kinto.core.schema.TimeStamp` instead.\"\"\"\n\n    def __init__(self, *args, **kwargs):\n        message = (\"`kinto.core.resource.schema.TimeStamp` is deprecated, \"\n                   \"use `kinto.core.schema.TimeStamp` instead.\")\n        warnings.warn(message, DeprecationWarning)\n        super(TimeStamp, self).__init__(*args, **kwargs)\n\n\nclass URL(URL):\n    \"\"\"This schema is deprecated, you shoud use `kinto.core.schema.URL` instead.\"\"\"\n\n    def __init__(self, *args, **kwargs):\n        message = (\"`kinto.core.resource.schema.URL` is deprecated, \"\n                   \"use `kinto.core.schema.URL` instead.\")\n        warnings.warn(message, DeprecationWarning)\n        super(URL, self).__init__(*args, **kwargs)\n\n\n# Resource related schemas\n\n\nclass ResourceSchema(colander.MappingSchema):\n    \"\"\"Base resource schema, with *Cliquet* specific built-in options.\"\"\"\n\n    class Options:\n        \"\"\"\n        Resource schema options.\n\n        This is meant to be overriden for changing values:\n\n        .. code-block:: python\n\n            class Product(ResourceSchema):\n                reference = colander.SchemaNode(colander.String())\n\n                class Options:\n                    readonly_fields = ('reference',)\n        \"\"\"\n        readonly_fields = tuple()\n        \"\"\"Fields that cannot be updated. Values for fields will have to be\n        provided either during record creation, through default values using\n        ``missing`` attribute or implementing a custom logic in\n        :meth:`kinto.core.resource.UserResource.process_record`.\n        \"\"\"\n\n        preserve_unknown = True\n        \"\"\"Define if unknown fields should be preserved or not.\n\n        The resource is schema-less by default. In other words, any field name\n        will be accepted on records. Set this to ``False`` in order to limit\n        the accepted fields to the ones defined in the schema.\n        \"\"\"\n\n    @classmethod\n    def get_option(cls, attr):\n        default_value = getattr(ResourceSchema.Options, attr)\n        return getattr(cls.Options, attr,  default_value)\n\n    @classmethod\n    def is_readonly(cls, field):\n        \"\"\"Return True if specified field name is read-only.\n\n        :param str field: the field name in the schema\n        :returns: ``True`` if the specified field is read-only,\n            ``False`` otherwise.\n        :rtype: bool\n        \"\"\"\n        return field in cls.get_option(\"readonly_fields\")\n\n    def schema_type(self):\n        if self.get_option(\"preserve_unknown\") is True:\n            unknown = 'preserve'\n        else:\n            unknown = 'ignore'\n        return colander.Mapping(unknown=unknown)\n\n\nclass PermissionsSchema(colander.SchemaNode):\n    \"\"\"A permission mapping defines ACEs.\n\n    It has permission names as keys and principals as values.\n\n    ::\n\n        {\n            \"write\": [\"fxa:af3e077eb9f5444a949ad65aa86e82ff\"],\n            \"groups:create\": [\"fxa:70a9335eecfe440fa445ba752a750f3d\"]\n        }\n\n    \"\"\"\n\n    def __init__(self, *args, **kwargs):\n        self.known_perms = kwargs.pop('permissions', tuple())\n        super(PermissionsSchema, self).__init__(*args, **kwargs)\n\n        for perm in self.known_perms:\n            self[perm] = self._get_node_principals(perm)\n\n    def schema_type(self):\n        if self.known_perms:\n            return colander.Mapping(unknown='raise')\n        else:\n            return colander.Mapping(unknown='preserve')\n\n    def deserialize(self, cstruct=colander.null):\n\n        # If permissions are not a mapping (e.g null or invalid), try deserializing\n        if not isinstance(cstruct, dict):\n            return super(PermissionsSchema, self).deserialize(cstruct)\n\n        # If permissions are listed, check fields and produce fancy error messages\n        if self.known_perms:\n            for perm in cstruct:\n                colander.OneOf(choices=self.known_perms)(self, perm)\n            return super(PermissionsSchema, self).deserialize(cstruct)\n\n        # Else deserialize the fields that are not on the schema\n        permissions = {}\n        perm_schema = colander.SequenceSchema(colander.SchemaNode(colander.String()))\n        for perm, principals in cstruct.items():\n            permissions[perm] = perm_schema.deserialize(principals)\n\n        return permissions\n\n    def _get_node_principals(self, perm):\n        principal = colander.SchemaNode(colander.String())\n        return colander.SchemaNode(colander.Sequence(), principal, name=perm,\n                                   missing=colander.drop)\n\n\n# Header schemas\n\n\nclass HeaderSchema(colander.MappingSchema):\n    \"\"\"Base schema used for validating and deserializing request headers. \"\"\"\n\n    missing = colander.drop\n\n    if_match = HeaderQuotedInteger(name='If-Match')\n    if_none_match = HeaderQuotedInteger(name='If-None-Match')\n\n    @staticmethod\n    def schema_type():\n        return colander.Mapping(unknown='preserve')\n\n\nclass PatchHeaderSchema(HeaderSchema):\n    \"\"\"Header schema used with PATCH requests.\"\"\"\n\n    def response_behavior_validator():\n        return colander.OneOf(['full', 'light', 'diff'])\n\n    response_behaviour = HeaderField(colander.String(), name='Response-Behavior',\n                                     validator=response_behavior_validator())\n\n\n# Querystring schemas\n\n\nclass QuerySchema(colander.MappingSchema):\n    \"\"\"\n    Schema used for validating and deserializing querystrings. It will include\n    and try to guess the type of unknown fields (field filters) on deserialization.\n    \"\"\"\n    missing = colander.drop\n\n    @staticmethod\n    def schema_type():\n        return colander.Mapping(unknown='ignore')\n\n    def deserialize(self, cstruct=colander.null):\n        \"\"\"\n        Deserialize and validate the QuerySchema fields and try to deserialize and\n        get the native value of additional filds (field filters) that may be present\n        on the cstruct.\n\n        e.g:: ?exclude_id=a,b&deleted=true -> {'exclude_id': ['a', 'b'], deleted: True}\n        \"\"\"\n        values = {}\n\n        schema_values = super(QuerySchema, self).deserialize(cstruct)\n        if schema_values is colander.drop:\n            return schema_values\n\n        # Deserialize querystring field filters (see docstring e.g)\n        for k, v in cstruct.items():\n            # Deserialize lists used on in_ and exclude_ filters\n            if k.startswith('in_') or k.startswith('exclude_'):\n                as_list = FieldList().deserialize(v)\n                if isinstance(as_list, list):\n                    values[k] = [native_value(v) for v in as_list]\n            else:\n                values[k] = native_value(v)\n\n        values.update(schema_values)\n        return values\n\n\nclass CollectionQuerySchema(QuerySchema):\n    \"\"\"Querystring schema used with collections.\"\"\"\n\n    _limit = QueryField(colander.Integer(), validator=positive_big_integer)\n    _sort = FieldList()\n    _token = QueryField(colander.String())\n    _since = QueryField(colander.Integer(), validator=positive_big_integer)\n    _to = QueryField(colander.Integer(), validator=positive_big_integer)\n    _before = QueryField(colander.Integer(), validator=positive_big_integer)\n    id = QueryField(colander.String())\n    last_modified = QueryField(colander.Integer(), validator=positive_big_integer)\n\n\nclass RecordGetQuerySchema(QuerySchema):\n    \"\"\"Querystring schema for GET record requests.\"\"\"\n\n    _fields = FieldList()\n\n\nclass CollectionGetQuerySchema(CollectionQuerySchema):\n    \"\"\"Querystring schema for GET collection requests.\"\"\"\n\n    _fields = FieldList()\n\n\n# Body Schemas\n\n\nclass RecordSchema(colander.MappingSchema):\n\n    @colander.deferred\n    def data(node, kwargs):\n        data = kwargs.get('data')\n        if data:\n            # Check if empty record is allowed.\n            # (e.g every schema fields have defaults)\n            try:\n                data.deserialize({})\n            except colander.Invalid:\n                pass\n            else:\n                data.default = {}\n                data.missing = colander.drop\n        return data\n\n    @colander.deferred\n    def permissions(node, kwargs):\n        def get_perms(node, kwargs):\n            return kwargs.get('permissions')\n        # Set if node is provided, else keep deferred. This allows binding the body\n        # on Resource first and bind permissions later if using SharableResource.\n        return get_perms(node, kwargs) or colander.deferred(get_perms)\n\n    @staticmethod\n    def schema_type():\n        return colander.Mapping(unknown='raise')\n\n\nclass JsonPatchOperationSchema(colander.MappingSchema):\n    \"\"\"Single JSON Patch Operation.\"\"\"\n\n    def op_validator():\n        op_values = ['test', 'add', 'remove', 'replace', 'move', 'copy']\n        return colander.OneOf(op_values)\n\n    def path_validator():\n        return colander.Regex('(/\\w*)+')\n\n    op = colander.SchemaNode(colander.String(), validator=op_validator())\n    path = colander.SchemaNode(colander.String(), validator=path_validator())\n    from_ = colander.SchemaNode(colander.String(), name='from',\n                                validator=path_validator(), missing=colander.drop)\n    value = colander.SchemaNode(Any(), missing=colander.drop)\n\n    @staticmethod\n    def schema_type():\n        return colander.Mapping(unknown='raise')\n\n\nclass JsonPatchBodySchema(colander.SequenceSchema):\n    \"\"\"Body used with JSON Patch (application/json-patch+json) as in RFC 6902.\"\"\"\n\n    operations = JsonPatchOperationSchema(missing=colander.drop)\n\n\n# Request schemas\n\n\nclass RequestSchema(colander.MappingSchema):\n    \"\"\"Base schema for kinto requests.\"\"\"\n\n    @colander.deferred\n    def header(node, kwargs):\n        return kwargs.get('header')\n\n    @colander.deferred\n    def querystring(node, kwargs):\n        return kwargs.get('querystring')\n\n    def after_bind(self, node, kw):\n        # Set default bindings\n        if not self.get('header'):\n            self['header'] = HeaderSchema()\n        if not self.get('querystring'):\n            self['querystring'] = QuerySchema()\n\n\nclass PayloadRequestSchema(RequestSchema):\n    \"\"\"Base schema for methods that use a JSON request body.\"\"\"\n\n    @colander.deferred\n    def body(node, kwargs):\n        def get_body(node, kwargs):\n            return kwargs.get('body')\n        # Set if node is provided, else keep deferred (and allow bindind later)\n        return get_body(node, kwargs) or colander.deferred(get_body)\n\n\nclass JsonPatchRequestSchema(RequestSchema):\n    \"\"\"JSON Patch (application/json-patch+json) request schema.\"\"\"\n\n    body = JsonPatchBodySchema()\n    querystring = QuerySchema()\n    header = PatchHeaderSchema()\n", "path": "kinto/core/resource/schema.py"}]}