Example #1
0
    def _get_app(self):
        self.config.include('cornice')

        failing_service = Service(name='failing', path='/fail')
        failing_service.add_view('GET', lambda r: 1 / 0)
        self.config.add_cornice_service(failing_service)

        return TestApp(CatchErrors(self.config.make_wsgi_app()))
Example #2
0
 def __init__(self, **kw):
     self._decorators = kw.pop('decorators', [timeit, incr_count,
                                              send_mozsvc_data])
     # To work properly with venusian, we have to specify the number of
     # frames between the call to venusian.attach and the definition of
     # the attached function.  Cornice defaults to 1, and we add another.
     kw.setdefault('depth', 2)
     Service.__init__(self, **kw)
 def test_fallback_no_required_csrf(self):
     service = Service(name='fallback-csrf', path='/', content_type='application/json')
     service.add_view('POST', lambda _:'', require_csrf=False)
     register_service_views(self.config, service)
     self.config.include('cornice')
     app = self.config.make_wsgi_app()
     testapp = TestApp(app)
     testapp.post('/', status=415, headers={'Content-Type': 'application/xml'})
 def test_fallback_no_predicate(self):
     service = Service(name='fallback-test', path='/',
                       effective_principals=('group:admins',))
     service.add_view('GET', lambda _:_)
     register_service_views(self.config, service)
     self.config.include('cornice')
     app = self.config.make_wsgi_app()
     testapp = TestApp(app)
     testapp.get('/', status=404)
Example #5
0
def includeme(config):
    # FIXME this should also work in includeme
    user_info = Service(name='users', path='/{username}/info')
    user_info.add_view('get', get_info)
    config.add_cornice_service(user_info)

    resource.add_view(ThingImp.collection_get, permission='read')
    thing_resource = resource.add_resource(
        ThingImp, collection_path='/thing', path='/thing/{id}',
        name='thing_service')
    config.add_cornice_resource(thing_resource)
    def setUp(self):
        self.config = testing.setUp()
        self.config.include("cornice")
        self.config.add_route('proute', '/from_pyramid')
        self.config.scan("tests.test_pyramidhook")

        def handle_response(request):
            return {'service': request.current_service.name,
                    'route': request.matched_route.name}
        rserv = Service(name="ServiceWPyramidRoute", pyramid_route="proute")
        rserv.add_view('GET', handle_response)

        register_service_views(self.config, rserv)
        self.app = TestApp(CatchErrors(self.config.make_wsgi_app()))
Example #7
0
    def __init__(self,
                 name=None, path=None, description=None, cors_policy=None, depth=0,
                 **kwargs):

        name = name or self.__class__.__name__.lower()

        CorniceService.__init__(
            self,
            name=name,
            path=path or '/{}'.format(name),
            description=description or 'service for {}'.format(path),
            cors_policy=cors_policy,
            depth=depth + 2,
            validators=self.validate,
            **kwargs
        )

        self.post()(self.receive)
    def test_fallback_permission(self):
        """
        Fallback view should be registered with NO_PERMISSION_REQUIRED
        Fixes: https://github.com/mozilla-services/cornice/issues/245
        """
        service = Service(name='fallback-test', path='/')
        service.add_view('GET', lambda _:_)
        register_service_views(self.config, service)

        # This is a bit baroque
        introspector = self.config.introspector
        views = introspector.get_category('views')
        fallback_views = [i for i in views
                          if i['introspectable']['route_name']=='fallback-test']

        for v in fallback_views:
            if v['introspectable'].title == u'function cornice.pyramidhook._fallback_view':
                permissions = [p['value'] for p in v['related'] if p.type_name == 'permission']
                self.assertIn(NO_PERMISSION_REQUIRED, permissions)
import colander
from cornice import Service
from cornice.service import get_services
from cornice.validators import colander_body_validator
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from cornice_swagger import CorniceSwagger

_VALUES = {}

# Create a simple service that will store and retrieve values
values = Service(name='foo', path='/values/{key}', description="Cornice Demo")


# Create a body schema for our requests
class BodySchema(colander.MappingSchema):
    value = colander.SchemaNode(colander.String(),
                                description='My precious value')


# Create a response schema for our 200 responses
class OkResponseSchema(colander.MappingSchema):
    body = BodySchema()


# Aggregate the response schemas for get requests
response_schemas = {'200': OkResponseSchema(description='Return value')}


# Create our cornice service views
class MyValueApi(object):
Example #10
0
from cornice import Service

from ngse.models import (Category, Form, form_category_association)

get_categories_service = Service('get categories',
                                 path='forms/categories',
                                 renderer='json')


@get_categories_service.get()
def get_categories(request):
    form_id = request.params.get('form_id')
    session = request.dbsession
    form = session.query(Form) \
        .filter(Form.id == form_id) \
        .one()

    result = []

    for category in session.query(Category).join(
            Category.form_type, aliased=True).filter_by(id=form.form_type_id):
        result.append({'id': category.id, 'name': category.name})

    return result


show_category_service = Service('get category',
                                path='forms/categories/show',
                                renderer='json')

Example #11
0
    Authenticated,
    remember,
    forget,
)
from pyramid.csrf import new_csrf_token

from cornice import Service

from ..models.usermaster import UserMaster
from ..models.boardmaster import BoardMaster
from . import cors

log = logging.getLogger(__name__)

svc_login = Service(name="api.login",
                    permission=NO_PERMISSION_REQUIRED,
                    path="/ui/login",
                    cors_policy=cors.POLICY)

svc_logout = Service(name="api.logout",
                     permission=NO_PERMISSION_REQUIRED,
                     path="/ui/logout",
                     cors_policy=cors.POLICY)

svc_whoami = Service(name="api.whoami",
                     permission=NO_PERMISSION_REQUIRED,
                     path="/ui/whoami",
                     cors_policy=cors.POLICY)


@svc_login.post(require_csrf=False)
def login(request):
Example #12
0
from operator import attrgetter

import cornice
import colander
from cornice import Service
from cornice.service import get_services
from pyramid.view import view_config
from cornice_swagger import CorniceSwagger
from cornice_swagger.converters import TypeConversionDispatcher
from cornice_swagger.converters.schema import BaseStringTypeConverter
from idris.utils import (colander_bound_repository_body_validator, JsonString,
                         Base64String)

# Create a service to serve our OpenAPI spec
swagger = Service(name='OpenAPI',
                  path='/__api__',
                  description="OpenAPI documentation")


def body_schema_transformer(schema, args):
    validators = args.get('validators', [])
    if colander_bound_repository_body_validator in validators:
        body_schema = schema
        schema = colander.MappingSchema()
        schema['body'] = body_schema
    return schema


class JSONStringTypeConverter(BaseStringTypeConverter):
    format = 'json'
Example #13
0
import glob
import collections
import datetime

import valideer as V

import conference_abstract.util
import conference_abstract.app_dao
from conference_abstract.auth import User

info_desc = """\
This is the registration page for the dna conference
"""

service = Service(name='loginEditor',
                  path='/loginEditor/{accessKey}',
                  description=info_desc)


def check_user(request):
    login = pyramid.security.authenticated_userid(request)
    user = None
    isValid = False
    if login is not None:
        username = login.split("|")[0]
        userId = login.split("|")[1]
        user = User(username)
        isValid = user.is_token_valid(userId)
        print "TESTING FOR SESSION", isValid
    if isValid == False:
        return False
Example #14
0
    def api(self, **kw):
        self._decorators.update(set(kw.pop('decorators', [])))

        return Service.api(self, **kw)
Example #15
0
        self.request = request

    def get_fresh_air(self):
        resp = Response()
        resp.body = 'air'
        return resp

    def make_it_fresh(self, response):
        response.body = 'fresh ' + response.body
        return response

    def check_temperature(self, request):
        if not 'X-Temperature' in request.headers:
            request.errors.add('header', 'X-Temperature')

tc = Service(name="TemperatureCooler", path="/fresh-air",
             klass=TemperatureCooler)
tc.add_view("GET", "get_fresh_air", filters=('make_it_fresh',),
            validators=('check_temperature',))


class TestService(TestCase):

    def setUp(self):
        self.config = testing.setUp()
        self.config.include("cornice")
        self.config.scan("cornice.tests.test_service")
        self.config.scan("cornice.tests.test_pyramidhook")
        self.app = TestApp(CatchErrors(self.config.make_wsgi_app()))

    def tearDown(self):
        testing.tearDown()
Example #16
0
 def __init__(self, **kw):
     self._decorators = kw.pop('decorators', [timeit, incr_count,
                                              send_mozsvc_data])
     Service.__init__(self, **kw)
Example #17
0
 def test(self):
     service = Service(name="test", path="/", schema=NonpickableSchema())
     service.add_view('GET', lambda _:_)
     register_service_views(self.config, service)
Example #18
0
        self.context = context

    def get_fresh_air(self):
        resp = Response()
        resp.text = u'air with ' + repr(self.context)
        return resp

    def make_it_fresh(self, response):
        response.text = u'fresh ' + response.text
        return response

    def check_temperature(self, request):
        if not 'X-Temperature' in request.headers:
            request.errors.add('header', 'X-Temperature')

tc = Service(name="TemperatureCooler", path="/fresh-air",
             klass=TemperatureCooler, factory=dummy_factory)
tc.add_view("GET", "get_fresh_air", filters=('make_it_fresh',),
            validators=('check_temperature',))


class TestService(TestCase):

    def setUp(self):
        self.config = testing.setUp()
        self.config.include("cornice")
        self.config.scan("cornice.tests.test_service")
        self.config.scan("cornice.tests.test_pyramidhook")
        self.app = TestApp(CatchErrors(self.config.make_wsgi_app()))

    def tearDown(self):
        testing.tearDown()
Example #19
0
    def get_fresh_air(self):
        resp = Response()
        resp.body = "air"
        return resp

    def make_it_fresh(self, response):
        response.body = "fresh " + response.body
        return response

    def check_temperature(self, request):
        if not "X-Temperature" in request.headers:
            request.errors.add("header", "X-Temperature")


tc = Service(name="TemperatureCooler", path="/fresh-air", klass=TemperatureCooler)
tc.add_view("GET", "get_fresh_air", filters=("make_it_fresh",), validators=("check_temperature",))


class TestService(TestCase):
    def setUp(self):
        self.config = testing.setUp()
        self.config.include("cornice")
        self.config.scan("cornice.tests.test_service")
        self.config.scan("cornice.tests.test_pyramidhook")
        self.app = TestApp(CatchErrors(self.config.make_wsgi_app()))

    def tearDown(self):
        testing.tearDown()

    def test_404(self):
Example #20
0
    DBSession,
    Asset,
    Character,
    CharacterFactory,
    CharacterQuery,
    CharacterLocalization,
    LibraryFactory,
    LibraryQuery,
    UserQuery,
)
from ..operations.script_export_default import OVERRIDABLE_CHARACTER_CONFIG_ITEMS
from . import check_is_language_valid
from ..operations import character as operations

character_in_story = Service(name='character_in_story',
                         path='story/{story_id}/character',
                         renderer='json')
character_in_library = Service(name='character_in_library',
                         path='library/{library_id}/character',
                         renderer='json',
                         factory=LibraryFactory,
                         traverse='/{library_id}')
character = Service(name='character',
                    path='character/{character_id}',
                    renderer='json',
                    factory=CharacterFactory,
                    traverse='/{character_id}')
character_id_language = Service(name='character_language',
                                path='character/{character_id}/character/{language}',
                                renderer='json',
                                factory=CharacterFactory,
Example #21
0
    validate_update_owner,
    validate_ignore_user,
    validate_comment_id,
    validate_username,
    validate_bug_feedback,
    validate_testcase_feedback,
    validate_captcha,
)
import bodhi.server.captcha
import bodhi.server.schemas
import bodhi.server.security
import bodhi.server.services.errors

comment = Service(name='comment',
                  path='/comments/{id}',
                  validators=(validate_comment_id, ),
                  description='Comment submission service',
                  cors_origins=bodhi.server.security.cors_origins_ro)

comments = Service(
    name='comments',
    path='/comments/',
    description='Comment submission service',
    # Note, this 'rw' is not a typo.  the @comments service has
    # a ``post`` section at the bottom.
    cors_origins=bodhi.server.security.cors_origins_rw)
comments_rss = Service(name='comments_rss',
                       path='/rss/comments/',
                       description='Comments RSS feed',
                       cors_origins=bodhi.server.security.cors_origins_ro)
Example #22
0
def get_catfact():
    """Get a cat fact from catfact.ninja and return it as a string.

    Functions for Soundhound, Google, IBM Watson, or other APIs can be added
    to create the desired functionality into this bot.

    """
    response = requests.get(CAT_FACTS_URL, verify=False)
    response.raise_for_status()
    json_data = response.json()
    return json_data['fact']


events_service = Service(
    name='events',
    path='/events',
    description="Webex Teams Webhook",
)


@events_service.get()
def get_events_service(request):
    log.info(get_catfact())
    return {"fact": get_catfact()}


# Your Webex Teams webhook should point to http://<serverip>:6543/events
@events_service.post()
def post_events_service(request):
    """Respond to inbound webhook JSON HTTP POST from Webex Teams."""
Example #23
0
from datetime import datetime, timedelta
from uuid import uuid4

from cornice import Service

from pjDb import Session, User
from pjLib.utilities import error_dict, hash_password

# Sphinx doc stuff
from pjDb.converters import dict_from_row

sessions_desc = """
Work with sessions for user accounts
"""
sessions_svc = Service(name='sessions',
                       path='/api/sessions',
                       description=sessions_desc)


@sessions_svc.post()
def sessions_post_view(request):
    """
    This will begin a new session given a username and password
    """
    if request.user is not None and request.json_body.get('token') is not None:
        # Our request validated their token, so just get that token
        return {'d': dict_from_row(request.dbsession.query(Session)\
                                   .filter(Session.token == request.json_body['token']).one())}
    username = request.json_body.get('username')
    if username is None or not isinstance(username, basestring):
        request.response.status = 400
Example #24
0
	def __init__(self,name,path,description,**kw):
		Service.__init__(self, name='users', path='/users', description="User registration", depth=2,**kw)
		pass
Example #25
0
def add_resource(klass, depth=1, **kw):
    """Function to declare resources of a Class.

    All the methods of this class named by the name of HTTP resources
    will be used as such. You can also prefix them by ``"collection_"`` and
    they will be treated as HTTP methods for the given collection path
    (collection_path), if any.

    :param klass:
        The class (resource) on which to register the service.

    :param depth:
        Which frame should be looked in default 2.

    :param kw:
        Keyword arguments configuring the resource.


    Here is an example:

    .. code-block:: python

        class User(object):
            pass

        add_resource(User, collection_path='/users', path='/users/{id}')

    Alternatively if you want to reuse your existing pyramid routes:

    .. code-block:: python

        class User(object):
            pass

        add_resource(User, collection_pyramid_route='users',
            pyramid_route='user')

    """

    services = {}

    if (('collection_pyramid_route' in kw or 'pyramid_route' in kw) and
            ('collection_path' in kw or 'path' in kw)):
        raise ValueError('You use either paths or route names, not both')

    if 'collection_path' in kw:
        if kw['collection_path'] == kw['path']:
            msg = "Warning: collection_path and path are not distinct."
            warnings.warn(msg)

        prefixes = ('', 'collection_')
    else:
        prefixes = ('',)

    if 'collection_pyramid_route' in kw:
        if kw['collection_pyramid_route'] == kw['pyramid_route']:
            msg = "Warning: collection_pyramid_route and " \
                  "pyramid_route are not distinct."
            warnings.warn(msg)

        prefixes = ('', 'collection_')

    for prefix in prefixes:

        # get clean view arguments
        service_args = {}
        for k in list(kw):
            if k.startswith('collection_'):
                if prefix == 'collection_':
                    service_args[k[len(prefix):]] = kw[k]
            elif k not in service_args:
                service_args[k] = kw[k]

        # auto-wire klass as its own view factory, unless one
        # is explicitly declared.
        if 'factory' not in kw:
            service_args['factory'] = klass

        # create service
        service_name = (service_args.pop('name', None) or
                        klass.__name__.lower())
        service_name = prefix + service_name
        service = services[service_name] = Service(name=service_name,
                                                   depth=2, **service_args)

        # initialize views
        for verb in ('get', 'post', 'put', 'delete', 'options', 'patch'):

            view_attr = prefix + verb
            meth = getattr(klass, view_attr, None)

            if meth is not None:
                # if the method has a __views__ arguments, then it had
                # been decorated by a @view decorator. get back the name of
                # the decorated method so we can register it properly
                views = getattr(meth, '__views__', [])
                if views:
                    for view_args in views:
                        service.add_view(verb, view_attr, klass=klass,
                                         **view_args)
                else:
                    service.add_view(verb, view_attr, klass=klass)

    setattr(klass, '_services', services)

    def callback(context, name, ob):
        # get the callbacks registered by the inner services
        # and call them from here when the @resource classes are being
        # scanned by venusian.
        for service in services.values():
            config = context.config.with_package(info.module)
            config.add_cornice_service(service)

    info = venusian.attach(klass, callback, category='pyramid', depth=depth)

    return klass
Example #26
0
from cornice import Service
from pyramid.security import NO_PERMISSION_REQUIRED

from kinto.events import ServerFlushed

flush = Service(name='flush',
                description='Clear database content',
                path='/__flush__')


@flush.post(permission=NO_PERMISSION_REQUIRED)
def flush_post(request):
    request.registry.storage.flush()
    request.registry.permission.flush()
    request.registry.cache.flush()
    event = ServerFlushed(request)
    request.registry.notify(event)

    request.response.status = 202
    return {}


def includeme(config):
    config.add_api_capability(
        'flush_endpoint',
        description='The __flush__ endpoint can be used to remove '
        'all data from all backends.',
        url='https://kinto.readthedocs.io/en/latest/api/1.x/flush.html')
    config.add_cornice_service(flush)
Example #27
0
    get_browserid_verifier,
    get_oauth_verifier
)
from tokenserver.assignment import INodeAssignment
from tokenserver.util import json_error, fxa_metrics_hash

import fxa.errors
import browserid.errors
import browserid.utils


logger = logging.getLogger("tokenserver")

# A GET on / returns the discovery API

discovery = Service(name='discovery', path='/')
token = Service(name='token', path='/1.0/{application}/{version}')

DEFAULT_TOKEN_DURATION = 5 * 60


def get_service_name(application, version):
    return "%s-%s" % (application, version)


@discovery.get()
def _discovery(request):
    """Returns a JSON file listing the services supported by the server."""
    services = request.registry.settings['tokenserver.applications']
    discovery = {}
    discovery["services"] = services
Example #28
0
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
import json

from pyramid.config import Configurator
from pyramid.httpexceptions import HTTPBadRequest

from cornice import Service

from .support import CatchErrors


# Service for testing callback-based validators.
service = Service(name="service", path="/service")


def has_payed(request, **kw):
    if 'paid' not in request.GET:
        request.errors.add('body', 'paid', 'You must pay!')


def foo_int(request, **kw):
    if 'foo' not in request.GET:
        return
    try:
        request.validated['foo'] = int(request.GET['foo'])
    except ValueError:
        request.errors.add('url', 'foo', 'Not an int')

Example #29
0
from dbas.handler.language import get_language_from_cookie
from dbas.strings.keywords import Keywords as _
from dbas.strings.translator import Translator
from dbas.validators.core import has_keywords_in_json_path, validate
from dbas.validators.discussion import valid_issue_by_id
from graph.lib import get_d3_data, get_opinion_data, get_path_of_user
from graph.partial_graph import get_partial_graph_for_argument, get_partial_graph_for_statement

LOG = logging.getLogger(__name__)
# =============================================================================
# SERVICES - Define services for several actions of D-BAS
# =============================================================================

complete_graph = Service(name='d3js_complete',
                         path='/complete',
                         description="D3JS Complete Dump")

partial_graph = Service(name='d3js_partial',
                        path='/partial',
                        description="D3JS Partial Dump")


# =============================================================================
# GRAPH-RELATED REQUESTS
# =============================================================================


@complete_graph.post()
@validate(valid_issue_by_id)
def get_d3_complete_dump(request):
Example #30
0
"""
Views for the Appearance objects.
"""
from webgnome_api.common.views import (get_object,
                                       create_object,
                                       update_object,
                                       cors_policy)

from cornice import Service

appearance = Service(name='appearance', path='/appearance*obj_id',
                description="appearance API", cors_policy=cors_policy)

implemented_types = (
    'gnome.utilities.appearance.Colormap',
    'gnome.utilities.appearance.MapAppearance',
    'gnome.utilities.appearance.MoverAppearance',
    'gnome.utilities.appearance.GridAppearance',
    'gnome.utilities.appearance.VectorAppearance',
    'gnome.utilities.appearance.Appearance',
    'gnome.utilities.appearance.SpillAppearance'
)


@appearance.get()
def get_appearance(request):
    '''Returns a Gnome appearance object in JSON.'''
    return get_object(request, implemented_types)


@appearance.post()
Example #31
0
import datetime

import valideer as V

import conference_abstract.util
import conference_abstract.app_dao
from conference_abstract.auth import User
import time
from conference_abstract.services.data.abstract_info import getAbstract

info_desc = """\
This is the abstract submission success
"""

service = Service(name='abstractSuccess',
                  path='/abstractSuccess/{abstractId}',
                  description=info_desc)


@service.get()
def service_get(request):
    login = pyramid.security.authenticated_userid(request)
    user = None
    templateVars = {}
    if login is not None:
        username = login.split("|")[0]
        user = conference_abstract.auth.check_user(request)
        abstractId = request.matchdict['abstractId']
        abstracts, authors = getAbstract(abstractId)
        abstract = None
        abstractAuthors = None
Example #32
0
from bodhi.server import log, security
from bodhi.server.models import Build, BuildrootOverride, Package, Release, User
from bodhi.server.validators import (
    validate_expiration_date,
    validate_override_builds,
    validate_override_notes,
    validate_packages,
    validate_releases,
    validate_username,
)
import bodhi.server.schemas
import bodhi.server.services.errors

override = Service(name='override',
                   path='/overrides/{nvr}',
                   description='Buildroot Overrides',
                   cors_origins=bodhi.server.security.cors_origins_ro)

overrides = Service(
    name='overrides',
    path='/overrides/',
    description='Buildroot Overrides',
    factory=security.PackagerACLFactory,
    # Note, this 'rw' is not a typo.  the @comments service has
    # a ``post`` section at the bottom.
    cors_origins=bodhi.server.security.cors_origins_rw)

overrides_rss = Service(name='overrides_rss',
                        path='/rss/overrides/',
                        description='Buildroot Overrides RSS Feed',
                        cors_origins=bodhi.server.security.cors_origins_ro)
Example #33
0
    validate_releases,
    validate_release,
    validate_username,
    validate_update_id,
    validate_requirements,
    validate_bugs,
    validate_request,
    validate_severity,
    validate_from_tag,
)
from bodhi.messages.schemas import update as update_schemas
import bodhi.server.notifications as notifications

update = Service(name='update',
                 path='/updates/{id}',
                 validators=(validate_update_id, ),
                 description='Update submission service',
                 factory=security.PackagerACLFactory,
                 cors_origins=bodhi.server.security.cors_origins_ro)

update_edit = Service(name='update_edit',
                      path='/updates/{id}/edit',
                      validators=(validate_update_id, ),
                      description='Update submission service',
                      factory=security.PackagerACLFactory,
                      cors_origins=bodhi.server.security.cors_origins_rw)

updates = Service(name='updates',
                  path='/updates/',
                  factory=security.PackagerACLFactory,
                  description='Update submission service',
                  cors_origins=bodhi.server.security.cors_origins_ro)
Example #34
0
    validate_build_tags,
    validate_acls,
    validate_builds,
    validate_enums,
    validate_releases,
    validate_release,
    validate_username,
    validate_update_id,
    validate_requirements,
    validate_bugs,
    validate_request,
)

update = Service(name='update',
                 path='/updates/{id}',
                 validators=(validate_update_id, ),
                 description='Update submission service',
                 acl=bodhi.security.packagers_allowed_acl,
                 cors_origins=bodhi.security.cors_origins_ro)

update_edit = Service(name='update_edit',
                      path='/updates/{id}/edit',
                      validators=(validate_update_id, ),
                      description='Update submission service',
                      acl=bodhi.security.packagers_allowed_acl,
                      cors_origins=bodhi.security.cors_origins_rw)

updates = Service(name='updates',
                  path='/updates/',
                  acl=bodhi.security.packagers_allowed_acl,
                  description='Update submission service',
                  cors_origins=bodhi.security.cors_origins_ro)
Example #35
0
    ReleaseState,
    TestGatingStatus,
)
from bodhi.server.validators import (
    validate_tags,
    validate_enums,
    validate_updates,
    validate_packages,
    validate_release,
)
import bodhi.server.schemas
import bodhi.server.services.errors


release = Service(name='release', path='/releases/{name}',
                  description='Fedora Releases',
                  cors_origins=bodhi.server.security.cors_origins_ro)
releases = Service(name='releases', path='/releases/',
                   description='Fedora Releases',
                   factory=security.AdminACLFactory,
                   # Note, this 'rw' is not a typo. The @releases service has
                   # a ``post`` section at the bottom.
                   cors_origins=bodhi.server.security.cors_origins_rw)


@release.get(accept="text/html", renderer="release.html",
             error_handler=bodhi.server.services.errors.html_handler)
def get_release_html(request):
    """
    Render a release given by id as HTML.
Example #36
0
        (Allow, 'alice', 'read'),
        (Allow, 'bob', 'write'),
        (Deny, 'carol', 'write'),
        (Allow, 'dan', ('write', 'update')),
    ]


class MyFactory(object):
    def __init__(self, request):
        self.request = request

    def __acl__(self):
        return my_acl(self.request)


service = Service(name="service", path="/service", factory=MyFactory)


@service.get()
def return_404(request):
    raise HTTPNotFound()


@service.put(permission='update')
def update_view(request):
    return "updated_view"


@service.delete(permission='write')
def return_yay(request):
    return "yay"
Example #37
0
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
from pyramid.config import Configurator

from cornice import Service
from cornice.tests import CatchErrors
import json

service = Service(name="service", path="/service")


def has_payed(request):
    if not 'paid' in request.GET:
        request.errors.add('body', 'paid', 'You must pay!')


def foo_int(request):
    if 'foo' not in request.GET:
        return
    try:
        request.validated['foo'] = int(request.GET['foo'])
    except ValueError:
        request.errors.add('url', 'foo', 'Not an int')


@service.get(validators=(has_payed, foo_int))
def get1(request):
    res = {"test": "succeeded"}
    try:
        res['foo'] = request.validated['foo']
Example #38
0
 def test_no_route_or_path(self):
     with self.assertRaises(TypeError):
         Service(name="broken service", )
Example #39
0
"""
Views for the Substance objects.
"""
from webgnome_api.common.views import (get_object, create_object,
                                       update_object, cors_policy)

from cornice import Service

substance = Service(name='substance',
                    path='/substance*obj_id',
                    description="Substance API",
                    cors_policy=cors_policy)

implemented_types = ('gnome.spill.substance.GnomeOil',
                     'gnome.spill.substance.NonWeatheringSubstance')


@substance.get()
def get_substance(request):
    '''Returns a Gnome Substance object in JSON.'''
    return get_object(request, implemented_types)


@substance.post()
def create_substance(request):
    '''Creates a Gnome Substance object.'''
    return create_object(request, implemented_types)


@substance.put()
def update_substance(request):
Example #40
0
 def test(self):
     # Compiled regexs are, apparently, non-pickleable
     service = Service(name="test", path="/", schema={'a': re.compile('')})
     service.add_view('GET', lambda _: _)
     register_service_views(self.config, service)
        self.context = context

    def get_fresh_air(self):
        resp = Response()
        resp.text = u'air with ' + repr(self.context)
        return resp

    def make_it_fresh(self, response):
        response.text = u'fresh ' + response.text
        return response

    def check_temperature(self, request, **kw):
        if not 'X-Temperature' in request.headers:
            request.errors.add('header', 'X-Temperature')

tc = Service(name="TemperatureCooler", path="/fresh-air",
             klass=TemperatureCooler, factory=dummy_factory)
tc.add_view("GET", "get_fresh_air", filters=('make_it_fresh',),
            validators=('check_temperature',))


class TestService(TestCase):

    def setUp(self):
        self.config = testing.setUp(
            settings={'pyramid.debug_authorization': True})

        # Set up debug_authorization logging to console
        logging.basicConfig(level=logging.DEBUG)
        debug_logger = logging.getLogger()
        self.config.registry.registerUtility(debug_logger, IDebugLogger)
Example #42
0
from sqlalchemy import func, distinct
from sqlalchemy.sql import or_

from bodhi.server import log, notifications, security
from bodhi.server.config import config
from bodhi.server.models import Package, Stack, Group, User
from bodhi.server.util import tokenize
from bodhi.server.validators import (validate_packages,
                                     validate_stack, validate_requirements)
import bodhi.server.schemas
import bodhi.server.services.errors


stack = Service(name='stack', path='/stacks/{name}',
                factory=security.PackagerACLFactory,
                validators=(validate_stack,),
                description='Bodhi Stacks',
                # Note, this 'rw' is not a typo.  there are deletes and posts.
                cors_origins=bodhi.server.security.cors_origins_rw)
stacks = Service(name='stacks', path='/stacks/',
                 description='Bodhi Stacks',
                 factory=security.PackagerACLFactory,
                 # Not a typo.  there are deletes and posts in here.
                 cors_origins=bodhi.server.security.cors_origins_rw)


@stack.get(accept="text/html", renderer="new_stack.html",
           error_handler=bodhi.server.services.errors.html_handler)
@stack.get(accept=('application/json', 'text/json'), renderer='json',
           error_handler=bodhi.server.services.errors.json_handler)
@stack.get(accept=('application/javascript'), renderer='jsonp',
           error_handler=bodhi.server.services.errors.jsonp_handler)
 def test(self):
     # Compiled regexs are, apparently, non-pickleable
     service = Service(name="test", path="/", schema={'a': re.compile('')})
     service.add_view('GET', lambda _:_)
     register_service_views(self.config, service)
Example #44
0
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
import json
from cornice import Service
from stokenserver.metadata import IMetadataDB

metadata = Service(name='metadata', path='/1.0/{service}')


def get_email(request):
    try:
        data = json.loads(request.body)
    except ValueError:
        request.errors.add('body', 'json', 'invalid json')
        return

    if 'email' not in data:
        request.errors.add('body', 'email', 'missing field')
    else:
        request.validated['email'] = data['email']

    request.validated['service'] = request.matchdict['service']


@metadata.post(validator=get_email)
def allocate_node(request):
    metadata_db = request.registry.queryUtility(IMetadataDB)
    uid, node = metadata_db.allocate_node(request.validated['email'],
                                          request.validated['service'])
    return {'node': node, 'uid': uid}
Example #45
0
# CORS configuration
# =============================================================================
cors_policy = dict(enabled=True,
                   headers=('Origin', 'X-Requested-With', 'Content-Type',
                            'Accept'),
                   origins=('*', ),
                   max_age=42)

# =============================================================================
# SERVICES - Define services for several actions of DBAS
# =============================================================================

debug_data = Service(
    name='debug',
    path='/debug',
    renderer='templates/overview.pt',
    description="Debug Data",
    permission='everybody',  # or permission='use'
    cors_policy=cors_policy)
debug_mail = Service(name='mail',
                     path='debug_mail',
                     description="Debug Mail",
                     renderer='json',
                     permission='admin',
                     cors_policy=cors_policy)

path = '/{url:.*}add',

# =============================================================================
# WEBSOCKET REQUESTS
# =============================================================================
Example #46
0
import collections
import datetime

import valideer as V

import conference_abstract.util
import conference_abstract.app_dao
from conference_abstract.auth import User
import time
import unicodedata

info_desc = """\
This will get the abstract info
"""
service = Service(name='abstractAssign',
                  path='/abstract/{abstractId}/assign',
                  description=info_desc)


def getAbstract(abstractId):
    conn = conference_abstract.util.get_connection()
    cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
    abstracts = []
    currentCategory = 0
    try:
        sql = """select title, abstract_type, abstract_text,
string_agg(replace(authorship.fname || ' ' || authorship.mname || ' ' || authorship.lname, '  ',' '), ', ') as authors
from abstracts 
left join authorship on abstracts.id = authorship.fk_abstract
where abstracts.id = %s
group by fk_abstract, title, abstract_type, abstract_text
Example #47
0
from cornice import Service
from colander import MappingSchema, SchemaNode, Int


class ScoreSchema(MappingSchema):
    score = SchemaNode(Int(), location="body", type='int')


hello = Service(name='hello', path='/', description="Simplest app")
scores = Service(name='scores', path='/scores')

SCORES = {}


@hello.get()
def get_info(request):
    """Returns Hello in JSON."""
    return {'Hello': 'World'}


@scores.post(schema=ScoreSchema)
def post_score(request):
    """Save score and return location in header."""

    request.response.status = 201
    request.response.headers['location'] = "10"
    SCORES["10"] = request.validated['score']
    return "ok"


@scores.get()
Example #48
0
 def __init__(self, **kw):
     Service.__init__(self, **kw)
     self._decorators = set()