Skip to content

Instantly share code, notes, and snippets.

@surabujin
Last active September 16, 2015 05:02
Show Gist options
  • Save surabujin/8109f55dd02b57c17fda to your computer and use it in GitHub Desktop.
Save surabujin/8109f55dd02b57c17fda to your computer and use it in GitHub Desktop.
cornice updated schema usage example
# -*- coding:utf-8 -*-
from __future__ import print_function, absolute_import
import cornice
from cornice import schemas
from colander import MappingSchema, SchemaNode, String, drop
from pyramid.config import Configurator
from wsgiref.simple_server import make_server
# adapter can be imported directly from schemas submodule, but in this case you
# should handle ImportError manually
ColanderAdapter = schemas.get_adapter('colander') # perhaps we should use some constant here
foobar = cornice.Service(name="foobar", path="/foobar")
class FooBarSchema(MappingSchema):
# foo and bar are required in the body (json), baz is optional
# yeah is required, but in the querystring.
foo = SchemaNode(String(), location="body")
bar = SchemaNode(String(), location="body")
baz = SchemaNode(String(), location="body", missing=drop)
yeah = SchemaNode(String(), location="querystring")
class GetSchema(MappingSchema):
yeah = SchemaNode(String(), location='querystring')
# use new cornice adapter
@foobar.post(schema=FooBarSchema)
def foobar_post(request):
return request.validated
# use backward compatible adapter
@foobar.put(schema=schemas.CorniceSchema.from_colander(
FooBarSchema, bind_request=False))
def foobar_put(request):
return request.validated
# use any preconfigured adapter
@foobar.patch(schema=ColanderAdapter(
FooBarSchema, bind_request=False, flattening=True))
def foobar_patch(request):
return request.validated
# use backward compatbile adapter (will use generic adapter lookup algorithm
# when we can drop out compatbility).
@foobar.get(schema='__main__.GetSchema')
def foobar_get(request):
return request.validated
def main():
config = Configurator()
config.include('cornice')
config.scan()
app = config.make_wsgi_app()
server = make_server('0.0.0.0', 8080, app)
server.serve_forever()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment