from cornice import Service from ..models import Client, Address, File, Task, Status from secrets import token_hex from pyramid.httpexceptions import HTTPNoContent, HTTPBadRequest, HTTPNotFound from pyramid.response import FileResponse from datetime import datetime from shutil import copyfileobj from errno import EEXIST import os import hashlib # Operator Endpoints raven_operator_list_clients = Service(name='ravenoplistclients', path='/api/game/commander', description='List all clients') raven_operator_cuid = Service(name='ravenopuid', path='/api/game/commander/{cuid}', description='Operator tasks with a single cuid') raven_operator_task = Service(name='ravenoptask', path='/api/game/commander/{cuid}/{tuid}', description='Single task in a cuid') # Client Endpoints raven_registration = Service(name='ravenreg', path='/api/game/login', description='Setup uid, key') raven_file_result_handler = Service( name='ravenupload',
from assembl.auth.util import get_permissions from assembl.tasks.translate import (translate_content, PrefCollectionTranslationTable) from assembl.models import (get_database_id, Post, AssemblPost, SynthesisPost, Synthesis, Discussion, Content, Idea, ViewPost, User, IdeaRelatedPostLink, AgentProfile, LangString, DummyContext, LanguagePreferenceCollection, SentimentOfPost) from assembl.models.post import deleted_publication_states from assembl.lib.raven_client import capture_message log = logging.getLogger('assembl') posts = Service( name='posts', path=API_DISCUSSION_PREFIX + '/posts', description="Post API following SIOC vocabulary as much as possible", renderer='json') post = Service(name='post', path=API_DISCUSSION_PREFIX + '/posts/{id:.+}', description="Manipulate a single post", renderer="json") post_read = Service(name='post_read', path=API_DISCUSSION_PREFIX + '/post_read/{id:.+}', description="Signal that a post was read", renderer='json') _ = TranslationStringFactory('assembl')
from cornice import Service hello = Service(name='hello', path='/', description="Simplest app") @hello.get() def get_info(request): """Returns Hello in JSON.""" return {'Hello': 'World'}
# 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') @service.get(validators=(has_payed, foo_int))
from cornice import Service from .huum_controller import Huum def huum_controller(request): settings = request.registry.settings huum_username = settings.get("huum.username") huum_password = settings.get("huum.password") huum_url = settings.get("huum.api_url") start_temp = settings.get("huum.start_temp") return Huum(huum_username, huum_password, huum_url, int(start_temp)) state = Service(name='targetHeatingCoolingState', path='/targetHeatingCoolingState/{state}', description="HomeBridge set state") status = Service(name='status', path='/status', description="HomeBridge status") targetTemperature = Service(name='targetTemperature', path='/targetTemperature/{temperature}', description="HomeBridge targetTemperature") targetRelativeHumidity = Service( name='targetRelativeHumidity', path='/targetRelativeHumidity/{targetRelativeHumidity}', description="HomeBridge targetRelativeHumidity") last_target = 0
from ..models import ( DBSession, Library, LibraryQuery, LibraryFactory, StoryQuery, User, UserQuery, PriceTier, PriceTierQuery, ) from ..operations import library as operations log = logging.getLogger(__name__) library = Service(name='library', path='library', renderer='json') library_id = Service(name='library_id', path='library/{library_id}', renderer='json', factory=LibraryFactory, traverse='/{library_id}') library_id_og = Service(name='library_id_og', path='library/{library_id}/og', renderer='json', factory=LibraryFactory, traverse='/{library_id}') library_id_selection = Service(name='library_id_selection', path='library/{library_id}/selection', renderer='json', factory=LibraryFactory, traverse='/{library_id}')
"""Define a service endpoint for searching for packages.""" import math from cornice import Service from cornice.validators import colander_querystring_validator from sqlalchemy import func, distinct from sqlalchemy.sql.expression import case from bodhi.server.models import Package import bodhi.server.schemas import bodhi.server.security import bodhi.server.services.errors packages = Service(name='packages', path='/packages/', description='PkgDB packages', cors_origins=bodhi.server.security.cors_origins_ro) @packages.get( schema=bodhi.server.schemas.ListPackageSchema, renderer='json', error_handler=bodhi.server.services.errors.json_handler, validators=(colander_querystring_validator,)) def query_packages(request): """ Search for packages via query string parameters. The following query string parameters may be used to limit the packages returned by the service: name: The name of the Packages you wish to retrieve. like: Search for Packages with names like the given string. search: Search for Packages with names like the given string, with case insensitivity.
def _configure_the_path(self, path): """Helper method to apply default configuration of the service path.""" # Insert pattern-matching regexes into the path path = path.replace("{collection}", "{collection:%s}" % (COLLECTION_ID_REGEX, )) path = path.replace("{item}", "{item:%s}" % (BSO_ID_REGEX, )) # Add path prefix for the API version number and userid. # XXX TODO: current FF client hardcodes "1.1" as the version number. # We accept it for now but should disable this eventually. path = "/{api:1\\.5}/{userid:[0-9]{1,10}}" + path return path # We define a simple "It Works!" view at the site root, so that # it's easy to see if the service is correctly running. site_root = Service(name="site_root", path="/") @site_root.get() def get_site_root(request): return "It Works! SyncStorage is successfully running on this host." # The /__lbheartbeat__ route is used by mozsvc load-balancer infra # to detect when a webhead is out of service. lbheartbeat = Service(name="lbheartbeat", path='/__lbheartbeat__', description="Web head health")
from restrepo import indexes import restrepo.indexes.ead from restrepo.storage import delete_file from restrepo.config import SERVICE_EAD_COLLECTION, SERVICE_EAD_ITEM from restrepo.config import SERVICE_EAD_ITEM_RAW from restrepo.utils import set_cors from restrepo.utils import now from restrepo.indexes.archivefile import cast_component_as_archivefile from restrepo.indexes import reindex_archivefiles from restrepo.db.archivefile import get_archivefiles from restrepo.db.archivefile import ArchiveFile from restrepo.db.archivefile import sort_field from restrepo import pagebrowser from restrepo.config import STATUS_PUBLISHED ead_service = Service(name=SERVICE_EAD_COLLECTION[1:], path=SERVICE_EAD_COLLECTION, description=__doc__) DTD = etree.DTD(StringIO(get_datafile('ead2002.dtd'))) def valid_xml_file(request): """check if the uploaded file is valid. we check: - XML validates - XML contains the necessary elements """ # we add a 'warnings' attribute, which we might use for user feedback (not implemented) if not hasattr(request, 'warnings'): request.warnings = []
import time import ujson import urllib import redis from docutils.core import publish_parts from cornice import Service from pyramid.httpexceptions import HTTPNotFound, HTTPBadRequest from webgnome_api.common.views import cors_exception, cors_policy from webgnome_api.common.indexing import iter_keywords help_svc = Service(name='help', path='/help*dir', description="Help Documentation and Feedback API", cors_policy=cors_policy) @help_svc.get() def get_help(request): '''Get the requested help file if it exists''' help_dir = get_help_dir_from_config(request) requested_dir = (urllib.unquote(sep.join( request.matchdict['dir'])).encode('utf8')) requested_file = join(help_dir, requested_dir) if isfile(requested_file + '.rst'): # a single help file was requested html = '' with open(requested_file + '.rst', 'r') as f:
import logging from cornice import Service from pyramid.httpexceptions import (HTTPBadRequest, HTTPNotFound) from adios_db_api.common.views import cors_policy, obj_id_from_url from adios_db.models.oil.product_type import PRODUCT_TYPES logger = logging.getLogger(__name__) product_types_api = Service(name='product-types', path='/product-types/*obj_id', description="Endpoint for getting product types", cors_policy=cors_policy) @product_types_api.get() def get_product_types(request): """ returns all the product types """ obj_id = obj_id_from_url(request) if obj_id is not None: try: obj_id = int(obj_id) except TypeError as e: logger.error(e) raise HTTPBadRequest('Bad Object ID')
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 import time info_desc = """\ This will get the abstract score info for a given chair """ service = Service(name='abstractSaveEdit', path='/abstract/{abstractId}/saveEdit/{accessKey}', 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 id, fk_submitter,review_status from abstracts where abstracts.id=%s """ print cur.mogrify(sql, (abstractId, )) cur.execute(sql, (abstractId, )) for row in cur.fetchall(): abstracts.append({ "id": row["id"],
from assembl.auth import ( P_READ, P_ADMIN_DISC, P_SYSADMIN, R_SYSADMIN, SYSTEM_ROLES) from assembl.auth.util import ( user_has_permission as a_user_has_permission, users_with_permission as a_users_with_permission) from social_pyramid.utils import load_backend, load_strategy cors_policy = dict( enabled=True, origins=('*',), credentials=True, max_age=86400, headers=('Location', 'Content-Type', 'Content-Length')) permissions = Service( name='permissions', path=API_DISCUSSION_PREFIX + '/permissions', description="The permissions for a given discussion", renderer='json', cors_policy=cors_policy ) permissions_for_role = Service( name='permissions_for_role', path=API_DISCUSSION_PREFIX + '/permissions/r/{role_name}', description="The permissions for a single role", renderer='json', cors_policy=cors_policy ) roles = Service( name='roles', path=API_DISCUSSION_PREFIX + '/roles', description="The roles defined in the system", renderer='json', cors_policy=cors_policy
from webgnome_api.common.common_object import (CreateObject, UpdateObject, ObjectImplementsOneOf, obj_id_from_url, obj_id_from_req_payload, get_file_path) from webgnome_api.common.session_management import (init_session_objects, get_session_objects, get_session_object, set_session_object, acquire_session_lock) from webgnome_api.common.helpers import JSONImplementsOneOf map_api = Service(name='map', path='/map*obj_id', description="Map API", cors_policy=cors_policy) implemented_types = ( 'gnome.maps.map.GnomeMap', 'gnome.maps.map.MapFromBNA', 'gnome.maps.map.ParamMap', ) log = logging.getLogger(__name__) @map_api.get() def get_map(request): '''Returns a Gnome Map object in JSON.''' content_requested = request.matchdict.get('obj_id')
""" Views for the Initializer objects. """ from webgnome_api.common.views import (get_object, create_object, update_object, cors_policy) from cornice import Service initializer = Service(name='initializer', path='/initializer*obj_id', description="Iinitializer API", cors_policy=cors_policy) module_name = 'gnome.spill.elements' module_attrs = ('InitWindages', 'InitMassFromPlume', 'InitRiseVelFromDist', 'InitRiseVelFromDropletSizeFromDist', ) implemented_types = ['{0}.{1}'.format(module_name, a) for a in module_attrs] @initializer.get() def get_initializer(request): '''Returns a Gnome Initializer object in JSON.''' return get_object(request, implemented_types) @initializer.post()
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 from conference_abstract.services.data.abstract_info import getAbstract info_desc = """\ This is the home page for brave """ service = Service(name='abstractNewdc', path='/abstractNewdc', description=info_desc) def getCategories(): conn = conference_abstract.util.get_connection() cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) sql = """select * from topics order by category, label;""" categories = [] categoryNames = [] currentCategory = 0 cur.execute(sql) for row in cur: categoryName = row['category'] if categoryName not in categoryNames: currentCategory = len(categoryNames) categoryNames.append(categoryName) categories.append([])
schema = WorkSchema() result = {'total': listing['total'], 'records': [schema.to_json(work.to_dict()) for work in listing['hits']], 'snippets': [], 'limit': limit, 'offset': offset, 'status': 'ok'} return result work_bulk = Service(name='WorkBulk', path='/api/v1/work/bulk', factory=ResourceFactory(WorkResource), api_security=[{'jwt':[]}], tags=['work'], cors_origins=('*', ), schema=WorkBulkRequestSchema(), validators=(colander_bound_repository_body_validator,), response_schemas={ '200': OKStatusResponseSchema(description='Ok'), '400': ErrorResponseSchema(description='Bad Request'), '401': ErrorResponseSchema(description='Unauthorized')}) @work_bulk.post(permission='import') def work_bulk_import_view(request): # get existing resources from submitted bulk keys = [r['id'] for r in request.validated['records'] if r.get('id')] existing_records = {r.id:r for r in request.context.get_many(keys) if r} models = [] for record in request.validated['records']: if record['id'] in existing_records: model = existing_records[record['id']]
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 import time info_desc = """\ This will get the unassign an editor """ service = Service(name='abstractEditorUnassign', path='/abstract/{abstractId}/unassignEditor', 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 id, fk_submitter,review_status from abstracts where abstracts.id=%s """ print cur.mogrify(sql, (abstractId, )) cur.execute(sql, (abstractId, )) for row in cur.fetchall(): abstracts.append({ "id": row["id"],
from ..operations.script_validator import ScriptValidator from ..operations.credit import get_story_credit from ..operations.image_handler import ComposeOgImage from ..operations.worker import KSBuildWorker from ..operations.block import count_words_of_block from ..operations.story import ( remove_story_localization, translate_story, translate_story_preview, ) log = logging.getLogger(__name__) story_language = Service(name='story_language', path='story/{story_id}/language/{language}', renderer='json', factory=StoryFactory, traverse='/{story_id}') story_translate = Service(name='story_translate', path='story/{story_id}/translate', renderer='json', factory=StoryFactory, traverse='/{story_id}') story_list = Service(name='story_list', path='story', renderer='json') tag_story = Service(name='tag_story', path='tag/story', renderer='json') story_id = Service(name='story_id', path='story/{story_id}', renderer='json', factory=StoryFactory, traverse='/{story_id}') story_validate = Service(name='story_validate',
ser = serial.Serial('/dev/ttyACM1', 9600) #ser.open() if ser.isOpen(): print "Listening on: ", ser.portstr else: sys.stderr.write('Failed to open serial on : %s\n' % ser.portstr) sys.exit(1) LEDS = range(5) COLORS = ['blue', 'green', 'yellow', 'red', 'lamp'] next_led_event = [time()] * len(LEDS) events = [[]] * len(LEDS) arduino = Service(name='arduino', path='/', description="Return the list of available leds") led = Service(name='led', path='/led/{id}', description="Return the list of available leds") class Event(object): def __init__(self, total, on, off): self.total = total / 100 self.on = on / 10 self.off = off / 10 def send_event(self, led): """Write the data to the API. StartByte LedNumber TotalTime (deciseconds) OnTime(hundredth
""" Views for the Weatherer objects. """ from webgnome_api.common.views import (get_object, create_object, update_object, cors_policy) from cornice import Service weatherer = Service(name='weatherer', path='/weatherer*obj_id', description="Weatherer API", cors_policy=cors_policy) implemented_types = ('gnome.weatherers.core.Weatherer', 'gnome.weatherers.Evaporation', 'gnome.weatherers.Emulsification', 'gnome.weatherers.Burn', 'gnome.weatherers.Skimmer', 'gnome.weatherers.NaturalDispersion', 'gnome.weatherers.Beaching', 'gnome.weatherers.ChemicalDispersion', 'gnome.weatherers.WeatheringData', 'gnome.weatherers.FayGravityViscous', 'gnome.weatherers.Dissolution' ) @weatherer.get() def get_weatherer(request): '''Returns a Gnome Weatherer object in JSON.''' return get_object(request, implemented_types)
from cornice_apispec import generate_spec class Schema(marshmallow.Schema): name = marshmallow.fields.String(required=True) response_schemas = { 200: Schema, } user_info = Service(name='users', path='/', validators=(marshmallow_body_validator,), apispec_show=True, apispec_response_schemas=response_schemas, description='Get and set user data.') @user_info.get() def get_info(request): return {'name': 'Name'} @view_config(route_name='openapi_spec', renderer='json') def api_spec(request): """Returns OpenApi dictionary for swagger. You need to pass a true request object for Pyramid Introspector work correctly.
Release, ) import bodhi.schemas import bodhi.security import bodhi.services.errors from bodhi.validators import ( validate_tags, validate_enums, validate_updates, validate_packages, validate_release, ) release = Service(name='release', path='/releases/{name}', description='Fedora Releases', cors_origins=bodhi.security.cors_origins_ro) releases = Service(name='releases', path='/releases/', description='Fedora Releases', # Note, this 'rw' is not a typo. the @comments service has # a ``post`` section at the bottom. cors_origins=bodhi.security.cors_origins_rw) @release.get(accept="text/html", renderer="release.html", error_handler=bodhi.services.errors.html_handler) def get_release_html(request): id = request.matchdict.get('name') release = Release.get(id, request.db) if not release: request.errors.add('body', 'name', 'No such release') request.errors.status = HTTPNotFound.code
from assembl.models import (AgentProfile, Extract, TextFragmentIdentifier, AnnotatorSource, Post, Webpage, Idea, AnnotationSelector) from assembl.auth.util import user_has_permission from assembl.lib.web_token import decode_token from assembl.lib import sqla cors_policy = dict(enabled=True, headers=('Location', 'Content-Type', 'Content-Length'), origins=('*', ), credentials=True, max_age=86400) extracts = Service( name='extracts', path=API_DISCUSSION_PREFIX + '/extracts', description="An extract from Content that is an expression of an Idea", renderer='json', cors_policy=cors_policy) extract = Service(name='extract', path=API_DISCUSSION_PREFIX + '/extracts/{id:.+}', description="Manipulate a single extract", renderer='json', cors_policy=cors_policy) search_extracts = Service(name='search_extracts', path=API_DISCUSSION_PREFIX + '/search_extracts', description="search for extracts matching a URL", renderer='json', cors_policy=cors_policy)
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)
@colander.instantiate() class types(colander.SequenceSchema): @colander.instantiate() class type(colander.MappingSchema): id = colander.SchemaNode(colander.String()) label = colander.SchemaNode(colander.String()) class ClientResponseSchema(colander.MappingSchema): body = ClientSchema() client = Service( name='Client', path='/api/v1/client', tags=['config'], cors_origins=('*', ), response_schemas={'200': ClientResponseSchema(description='Ok')}) def generate_client_config(repo): group_types = repo.type_config('group_type') work_types = repo.type_config('work_type') work_types.sort(key=itemgetter('label')) group_account_types = repo.type_config('group_account_type') person_account_types = repo.type_config('person_account_type') identifier_types = repo.type_config('identifier_type') description_types = repo.type_config('description_type') description_formats = repo.type_config('description_format') expression_types = repo.type_config('expression_type') expression_formats = repo.type_config('expression_format')
""" Views for the Release objects. """ from .common_object import get_object, create_or_update_object from cornice import Service release = Service(name='release', path='/release*obj_id', description="Release API") implemented_types = ( 'gnome.spill.release.Release', 'gnome.spill.release.PointLineRelease', 'gnome.spill.release.SpatialRelease', 'gnome.spill.release.VerticalPlumeRelease', ) @release.get() def get_environment(request): '''Returns a Gnome Release object in JSON.''' return get_object(request, implemented_types) @release.put() def create_or_update_environment(request): '''Creates or Updates a Gnome Release object.''' return create_or_update_object(request, implemented_types)
from cornice import Service from pyramid.httpexceptions import HTTPForbidden from ..models import ( DBSession, UserFactory, UserQuery, UserLink, UserLinkFactory, UserLinkTypeQuery, ) user_links_types = Service(name='user_links_types', path='user/links/types', renderer='json') user_id_links = Service(name='user_id_links', path='user/{user_id}/links', renderer='json', factory=UserFactory, traverse='/{user_id}') user_links = Service(name='user_links', path='user/links', renderer='json') user_link_id = Service(name='user_link_id', path='user/link/{user_link_id}', renderer='json',
from sqlalchemy.sql import or_ from bodhi import log from bodhi.models import Build, BuildrootOverride, Package, Release, User import bodhi.schemas import bodhi.services.errors from bodhi.validators import ( validate_override_builds, validate_expiration_date, validate_packages, validate_releases, validate_username, ) override = Service(name='override', path='/overrides/{nvr}', description='Buildroot Overrides', cors_origins=bodhi.security.cors_origins_ro) overrides = Service( name='overrides', path='/overrides/', description='Buildroot Overrides', # Note, this 'rw' is not a typo. the @comments service has # a ``post`` section at the bottom. cors_origins=bodhi.security.cors_origins_rw) overrides_rss = Service(name='overrides_rss', path='/rss/overrides/', description='Buildroot Overrides RSS Feed', cors_origins=bodhi.security.cors_origins_ro)
""" import re import logging from cornice import Service from pyramid.httpexceptions import HTTPNotFound from sqlalchemy.orm.exc import NoResultFound from ..common.views import cors_policy, obj_id_from_url from oil_library import _get_db_session from oil_library.models import Oil, ImportedRecord from oil_library.oil_props import OilProps oil_api = Service(name='oil', path='/oil*obj_id', description="List All Oils", cors_policy=cors_policy) logger = logging.getLogger(__name__) def memoize_oil_arg(func): res = {} def memoized_func(oil): if oil.adios_oil_id not in res: logger.info('loading in-memory oil dict. Key: "{}"' .format(oil.adios_oil_id)) res[oil.adios_oil_id] = func(oil) return res[oil.adios_oil_id]