def CreateWsgiApplication(self):
     """Create WSGI application used on the server side for testing."""
     return service.service_mappings([
         ('/my/service', webapp_test_util.TestService),
         ('/my/other_service',
          webapp_test_util.TestService.new_factory('initialized'))
     ])
Esempio n. 2
0
  def __init__(self, api_services, **kwargs):
    """Initialize an _ApiServer instance.

    The primary function of this method is to set up the WSGIApplication
    instance for the service handlers described by the services passed in.
    Additionally, it registers each API in ApiConfigRegistry for later use
    in the BackendService.getApiConfigs() (API config enumeration service).

    Args:
      api_services: List of protorpc.remote.Service classes implementing the API
      **kwargs: Passed through to protorpc.wsgi.service.service_handlers except:
        protocols - ProtoRPC protocols are not supported, and are disallowed.
        restricted - If True or unset, the API will only be allowed to serve to
          Google's API serving infrastructure once deployed.  Set to False to
          allow other clients.  Under dev_appserver, all clients are accepted.
          NOTE! Under experimental launch, this is not a secure restriction and
          other authentication mechanisms *must* be used to control access to
          the API.  The restriction is only intended to notify developers of
          a possible upcoming feature to securely restrict access to the API.

    Raises:
      TypeError: if protocols are configured (this feature is not supported).
      ApiConfigurationError: if there's a problem with the API config.
    """
    protorpc_services = []
    generator = api_config.ApiConfigGenerator()
    self.api_config_registry = api_backend_service.ApiConfigRegistry()
    api_name_version_map = {}
    for service in api_services:
      key = (service.api_info.name, service.api_info.version)
      services = api_name_version_map.setdefault(key, [])
      if service in services:
        raise api_config.ApiConfigurationError(
            'Can\'t add the same class to an API twice: %s' % service.__name__)
      services.append(service)

    for services in api_name_version_map.values():
      config_file = generator.pretty_print_config_to_json(services)



      self.api_config_registry.register_spi(config_file)
      for api_service in services:
        protorpc_class_name = api_service.__name__
        root = self.__SPI_PREFIX + protorpc_class_name
        if not any(service[0] == root or service[1] == api_service
                   for service in protorpc_services):
          protorpc_services.append((root, api_service))


    backend_service = api_backend_service.BackendServiceImpl.new_factory(
        self.api_config_registry, _get_app_revision())
    protorpc_services.insert(0, (self.__BACKEND_SERVICE_ROOT, backend_service))

    if 'protocols' in kwargs:
      raise TypeError('__init__() got an unexpected keyword argument '
                      "'protocols'")
    self.restricted = kwargs.pop('restricted', True)
    self.service_app = wsgi_service.service_mappings(protorpc_services,
                                                     **kwargs)
Esempio n. 3
0
 def  CreateWsgiApplication(self):
   """Create WSGI application used on the server side for testing."""
   return service.service_mappings(
     [('/my/service', webapp_test_util.TestService),
      ('/my/other_service',
       webapp_test_util.TestService.new_factory('initialized'))
     ])
Esempio n. 4
0
    def __init__(self, api_services, **kwargs):
        """Initialize an _ApiServer instance.

    The primary function of this method is to set up the WSGIApplication
    instance for the service handlers described by the services passed in.
    Additionally, it registers each API in ApiConfigRegistry for later use
    in the BackendService.getApiConfigs() (API config enumeration service).

    Args:
      api_services: List of protorpc.remote.Service classes implementing the API
      **kwargs: Passed through to protorpc.wsgi.service.service_handlers except:
        protocols - ProtoRPC protocols are not supported, and are disallowed.
        restricted - If True or unset, the API will only be allowed to serve to
          Google's API serving infrastructure once deployed.  Set to False to
          allow other clients.  Under dev_appserver, all clients are accepted.
          NOTE! Under experimental launch, this is not a secure restriction and
          other authentication mechanisms *must* be used to control access to
          the API.  The restriction is only intended to notify developers of
          a possible upcoming feature to securely restrict access to the API.

    Raises:
      TypeError: if protocols are configured (this feature is not supported).
      ApiConfigurationError: if there's a problem with the API config.
    """
        protorpc_services = []
        generator = api_config.ApiConfigGenerator()
        self.api_config_registry = api_backend_service.ApiConfigRegistry()
        api_name_version_map = {}
        for service in api_services:
            key = (service.api_info.name, service.api_info.version)
            services = api_name_version_map.setdefault(key, [])
            if service in services:
                raise api_config.ApiConfigurationError(
                    'Can\'t add the same class to an API twice: %s' %
                    service.__name__)
            services.append(service)

        for services in api_name_version_map.values():
            config_file = generator.pretty_print_config_to_json(services)

            self.api_config_registry.register_spi(config_file)
            for api_service in services:
                protorpc_class_name = api_service.__name__
                root = self.__SPI_PREFIX + protorpc_class_name
                if not any(service[0] == root or service[1] == api_service
                           for service in protorpc_services):
                    protorpc_services.append((root, api_service))

        backend_service = api_backend_service.BackendServiceImpl.new_factory(
            self.api_config_registry, _get_app_revision())
        protorpc_services.insert(
            0, (self.__BACKEND_SERVICE_ROOT, backend_service))

        if 'protocols' in kwargs:
            raise TypeError('__init__() got an unexpected keyword argument '
                            "'protocols'")
        self.restricted = kwargs.pop('restricted', True)
        self.service_app = wsgi_service.service_mappings(
            protorpc_services, **kwargs)
 def testNoRegistry(self):
     self.ResetServer(
         service.service_mappings(
             [('/my/service', webapp_test_util.TestService),
              ('/my/other_service',
               webapp_test_util.TestService.new_factory('initialized'))],
             registry_path=None))
     registry_client = self.GetRegistryStub()
     self.assertRaisesWithRegexpMatch(remote.ServerError,
                                      'HTTP Error 404: Not Found',
                                      registry_client.services)
Esempio n. 6
0
  def __init__(self, api_services, **kwargs):
    """Initialize an _ApiServer instance.

    The primary function of this method is to set up the WSGIApplication
    instance for the service handlers described by the services passed in.
    Additionally, it registers each API in ApiConfigRegistry for later use
    in the BackendService.getApiConfigs() (API config enumeration service).

    Args:
      api_services: List of protorpc.remote.Service classes implementing the API
        or a list of _ApiDecorator instances that decorate the service classes
        for an API.
      **kwargs: Passed through to protorpc.wsgi.service.service_handlers except:
        protocols - ProtoRPC protocols are not supported, and are disallowed.

    Raises:
      TypeError: if protocols are configured (this feature is not supported).
      ApiConfigurationError: if there's a problem with the API config.
    """
    self.base_paths = set()

    for entry in api_services[:]:
      # pylint: disable=protected-access
      if isinstance(entry, api_config._ApiDecorator):
        api_services.remove(entry)
        api_services.extend(entry.get_api_classes())
        self.base_paths.add(entry.base_path)

    # Record the API services for quick discovery doc generation
    self.api_services = api_services

    # Record the base paths
    for entry in api_services:
      self.base_paths.add(entry.api_info.base_path)

    self.api_config_registry = api_backend_service.ApiConfigRegistry()
    self.api_name_version_map = self.__create_name_version_map(api_services)
    protorpc_services = self.__register_services(self.api_name_version_map,
                                                 self.api_config_registry)

    # Disallow protocol configuration for now, Lily is json-only.
    if 'protocols' in kwargs:
      raise TypeError('__init__() got an unexpected keyword argument '
                      "'protocols'")
    protocols = remote.Protocols()
    protocols.add_protocol(self.__PROTOJSON, 'protojson')
    remote.Protocols.set_default(protocols)

    # This variable is not used in Endpoints 1.1, but let's pop it out here
    # so it doesn't result in an unexpected keyword argument downstream.
    kwargs.pop('restricted', None)

    self.service_app = wsgi_service.service_mappings(protorpc_services,
                                                     **kwargs)
Esempio n. 7
0
  def __init__(self, api_services, **kwargs):
    """Initialize an _ApiServer instance.

    The primary function of this method is to set up the WSGIApplication
    instance for the service handlers described by the services passed in.
    Additionally, it registers each API in ApiConfigRegistry for later use
    in the BackendService.getApiConfigs() (API config enumeration service).

    Args:
      api_services: List of protorpc.remote.Service classes implementing the API
        or a list of _ApiDecorator instances that decorate the service classes
        for an API.
      **kwargs: Passed through to protorpc.wsgi.service.service_handlers except:
        protocols - ProtoRPC protocols are not supported, and are disallowed.
        restricted - If True or unset, the API will only be allowed to serve to
          Google's API serving infrastructure once deployed.  Set to False to
          allow other clients.  Under dev_appserver, all clients are accepted.
          NOTE! Under experimental launch, this is not a secure restriction and
          other authentication mechanisms *must* be used to control access to
          the API.  The restriction is only intended to notify developers of
          a possible upcoming feature to securely restrict access to the API.

    Raises:
      TypeError: if protocols are configured (this feature is not supported).
      ApiConfigurationError: if there's a problem with the API config.
    """
    for entry in api_services[:]:

      if isinstance(entry, api_config._ApiDecorator):
        api_services.remove(entry)
        api_services.extend(entry.get_api_classes())

    self.api_config_registry = api_backend_service.ApiConfigRegistry()
    api_name_version_map = self.__create_name_version_map(api_services)
    protorpc_services = self.__register_services(api_name_version_map,
                                                 self.api_config_registry)


    backend_service = api_backend_service.BackendServiceImpl.new_factory(
        self.api_config_registry, _get_app_revision())
    protorpc_services.insert(0, (self.__BACKEND_SERVICE_ROOT, backend_service))


    if 'protocols' in kwargs:
      raise TypeError('__init__() got an unexpected keyword argument '
                      "'protocols'")
    protocols = remote.Protocols()
    protocols.add_protocol(self.__PROTOJSON, 'protojson')
    remote.Protocols.set_default(protocols)

    self.restricted = kwargs.pop('restricted', True)
    self.service_app = wsgi_service.service_mappings(protorpc_services,
                                                     **kwargs)
Esempio n. 8
0
 def testNoRegistry(self):
   self.ResetServer(service.service_mappings(
     [('/my/service', webapp_test_util.TestService),
      ('/my/other_service',
       webapp_test_util.TestService.new_factory('initialized'))
     ],
     registry_path=None))
   registry_client = self.GetRegistryStub()
   self.assertRaisesWithRegexpMatch(
     remote.ServerError,
     'HTTP Error 404: Not Found',
     registry_client.services)
Esempio n. 9
0
def api_server(api_services):
    """Set up an WSGIApplication instance for the API services provided.

    https://github.com/cloudendpoints/endpoints-python/blob/9da60817aefbb0f2a4b9145c17ee39b9115067b0/endpoints/apiserving.py#L541
    """
    services = []
    for service_class in api_services:
        service_path = '{}{}/{}'.format(service_class.wrapper_api_base_path,
                                        service_class.wrapper_api_name,
                                        service_class.wrapper_api_version)
        services.append((service_path, service_class))
    return service.service_mappings(services)
Esempio n. 10
0
def application(environ, start_response):
    urlfetch.set_default_fetch_deadline(60)
    import_services()
    response = None

    if environ.get('REQUEST_METHOD') in ["OPTIONS"]:
        start_response('200 OK',
                       [('Access-Control-Allow-Headers',
                         'authorization, origin, content-type, accept'),
                        ('Access-Control-Max-Age', '600'),
                        ('Access-Control-Allow-Origin', '*')])
        response = ['']
    elif environ.get('REQUEST_METHOD') in ["GET", "HEAD", "POST"]:
        swagger = swagger2(environ.get('HTTP_HOST'), environ.get('PATH_INFO'))

        if swagger:
            start_response('200 OK', [('Content-type', 'application/json'),
                                      ('Access-Control-Allow-Origin', '*')])
            response = [swagger]
        else:
            app = service.service_mappings([(s.path, s) for s in SERVICES],
                                           registry_path=None)
            query = dict(urlparse.parse_qsl(environ.get('QUERY_STRING')))

            if environ.get('REQUEST_METHOD') in [
                    "GET", "HEAD"
            ] and environ.get('QUERY_STRING'):
                content = json.dumps(query)
                environ['wsgi.input'] = StringIO.StringIO(content)
                environ['CONTENT_LENGTH'] = len(content)

            environ['REQUEST_METHOD'] = 'POST'
            environ['CONTENT_TYPE'] = 'application/json'

            if environ.get('HTTP_AUTHORIZATION') is None and query.get(
                    "authorization") is not None:
                environ['HTTP_AUTHORIZATION'] = query.get("authorization")

            def _start_response(status, response_headers):
                response_headers.append(('Access-Control-Allow-Origin', '*'))
                return start_response(status, response_headers)

            response = app(environ, _start_response)
    else:
        start_response('405 Method Not Allowed',
                       [('Allow', 'OPTIONS, GET, HEAD, POST')])
        response = ['']

    if environ.get('REQUEST_METHOD') in ["HEAD"]:
        return ['']
    else:
        return response
Esempio n. 11
0
def CreateWSGIApplication(pod=None):
  podserver_app = webapp2.WSGIApplication([
      ('/.*', handlers.PodHandler),
  ])
  podserver_app.registry['pod'] = pod
  routes = [
      ('/_api/pods.*', services.PodService),
  ]
  return service.service_mappings(
      routes,
      service_prefix='/_api',
      registry_path='/_api/protorpc',
      append_wsgi_apps=[podserver_app])
Esempio n. 12
0
 def testRegistryDictionary(self):
   self.ResetServer(service.service_mappings(
     {'/my/service': webapp_test_util.TestService,
      '/my/other_service':
          webapp_test_util.TestService.new_factory('initialized'),
     }))
   registry_client = self.GetRegistryStub()
   response = registry_client.services()
   self.assertIterEqual([
       registry.ServiceMapping(
           name='/my/other_service',
           definition='protorpc.webapp_test_util.TestService'),
       registry.ServiceMapping(
           name='/my/service',
           definition='protorpc.webapp_test_util.TestService'),
       ], response.services)
Esempio n. 13
0
 def testRegistryDictionary(self):
     self.ResetServer(
         service.service_mappings({
             '/my/service':
             webapp_test_util.TestService,
             '/my/other_service':
             webapp_test_util.TestService.new_factory('initialized'),
         }))
     registry_client = self.GetRegistryStub()
     response = registry_client.services()
     self.assertIterEqual([
         registry.ServiceMapping(
             name='/my/other_service',
             definition='protorpc.webapp_test_util.TestService'),
         registry.ServiceMapping(
             name='/my/service',
             definition='protorpc.webapp_test_util.TestService'),
     ], response.services)
Esempio n. 14
0
 def testAltRegistry(self):
     self.ResetServer(
         service.service_mappings(
             [('/my/service', webapp_test_util.TestService),
              ('/my/other_service',
               webapp_test_util.TestService.new_factory('initialized'))],
             registry_path='/registry'))
     registry_client = self.GetRegistryStub('/registry')
     services = registry_client.services()
     self.assertTrue(isinstance(services, registry.ServicesResponse))
     self.assertIterEqual([
         registry.ServiceMapping(
             name='/my/other_service',
             definition='protorpc.webapp_test_util.TestService'),
         registry.ServiceMapping(
             name='/my/service',
             definition='protorpc.webapp_test_util.TestService'),
     ], services.services)
Esempio n. 15
0
def CreateWSGIApplication(pod=None, debug=False):
  podserver_app = WSGIApplication([
      ('/_grow/translations/(.*)', handlers.CatalogHandler),
      ('/_grow/translations', handlers.CatalogsHandler),
      ('/_grow/content', handlers.CollectionsHandler),
      ('/_grow', handlers.ConsoleHandler),
      ('/.*', handlers.PodHandler),
  ], debug=debug)
  podserver_app.registry['pod'] = pod
  api_routes = []
  api_app = service.service_mappings(
      api_routes,
      service_prefix='/_api',
      registry_path='/_api/protorpc',
      append_wsgi_apps=[podserver_app])
  static_path = os.path.join(utils.get_grow_dir(), 'server', 'frontend')
  return wsgi.SharedDataMiddleware(api_app, {
      '/_grow/static': static_path,
  })
Esempio n. 16
0
  def testRegex(self):
    self.ResetServer(service.service_mappings(
      [('/my/[0-9]+', webapp_test_util.TestService.new_factory('service')),
       ('/my/[a-z]+',
            webapp_test_util.TestService.new_factory('other-service')),
      ]))
    my_service_url = 'http://localhost:%d/my/12345' % self.port
    my_other_service_url = 'http://localhost:%d/my/blarblar' % self.port

    my_service = webapp_test_util.TestService.Stub(
      transport.HttpTransport(my_service_url))
    my_other_service = webapp_test_util.TestService.Stub(
      transport.HttpTransport(my_other_service_url))

    response = my_service.init_parameter()
    self.assertEquals('service', response.string_value)

    response = my_other_service.init_parameter()
    self.assertEquals('other-service', response.string_value)
Esempio n. 17
0
 def testAltRegistry(self):
   self.ResetServer(service.service_mappings(
     [('/my/service', webapp_test_util.TestService),
      ('/my/other_service',
       webapp_test_util.TestService.new_factory('initialized'))
     ],
     registry_path='/registry'))
   registry_client = self.GetRegistryStub('/registry')
   services = registry_client.services()
   self.assertTrue(isinstance(services, registry.ServicesResponse))
   self.assertIterEqual(
       [registry.ServiceMapping(
           name='/my/other_service',
           definition='protorpc.webapp_test_util.TestService'),
        registry.ServiceMapping(
            name='/my/service',
            definition='protorpc.webapp_test_util.TestService'),
       ],
       services.services)
Esempio n. 18
0
    def testRegex(self):
        self.ResetServer(
            service.service_mappings([
                ('/my/[0-9]+',
                 webapp_test_util.TestService.new_factory('service')),
                ('/my/[a-z]+',
                 webapp_test_util.TestService.new_factory('other-service')),
            ]))
        my_service_url = 'http://localhost:%d/my/12345' % self.port
        my_other_service_url = 'http://localhost:%d/my/blarblar' % self.port

        my_service = webapp_test_util.TestService.Stub(
            transport.HttpTransport(my_service_url))
        my_other_service = webapp_test_util.TestService.Stub(
            transport.HttpTransport(my_other_service_url))

        response = my_service.init_parameter()
        self.assertEquals('service', response.string_value)

        response = my_other_service.init_parameter()
        self.assertEquals('other-service', response.string_value)
Esempio n. 19
0
from protorpc import messages
from protorpc import remote
from protorpc.wsgi import service
from team import Team
import logging

package = 'SaintsSchedule'


# Create the request string containing the user's name
class ScheduleRequest(messages.Message):
    team_id = messages.StringField(1, required=True)


# Create the response string
class ScheduleResponse(messages.Message):
    schedule = messages.StringField(1, required=True)


# Create the RPC service to exchange messages
class ScheduleService(remote.Service):
    @remote.method(ScheduleRequest, ScheduleResponse)
    def schedule(self, request):
        t = Team()
        games = t.getGames(request.team_id)
        return ScheduleResponse(schedule=games)


# Map the RPC service and path (/schedule)
app = service.service_mappings([('/schedule.*', ScheduleService)])
from protorpc.wsgi import service

import archiveservice

# Map the RPC service and path (/ArchiveService)
app = service.service_mappings([('/ArchiveService', archiveservice.ArchiveService)])
Esempio n. 21
0
class SeasonRequest(messages.Message):
    seasonRequest = messages.StringField(1, required=False)


# Create the response string
class SeasonResponse(messages.Message):
    seasons = messages.MessageField(Season, 1, repeated=True)


# Create the RPC service to exchange messages
class SeasonService(remote.Service):
    @remote.method(SeasonRequest, SeasonResponse)
    def season(self, request):
        theCache = memcache.get("seasons")
        if theCache is None:
            t = Team()
            seasons = []
            for team in t.getSeasons():
                season = Season(season=team.season)
                if season not in seasons:
                    seasons.append(season)
            if not memcache.add("seasons", seasons):
                logging.error("memcache failed to set")
            return SeasonResponse(seasons=seasons)
        else:
            return SeasonResponse(seasons=theCache)


# Map the RPC service and path (/schedule)
app = service.service_mappings([("/season.*", SeasonService)])
Esempio n. 22
0
from protorpc.wsgi import service as wsgi_service

from api import maps

service = wsgi_service.service_mappings([
    ('/api/maps', maps.PostService),
])
Esempio n. 23
0
from protorpc import remote
from protorpc.wsgi import service


class IncrementLapRequest(messages.Message):
  """Request to increment the lap count."""
  barcode_number = messages.IntegerField(1)
  increment_by = messages.IntegerField(2, default=1)
  validate = messages.BooleanField(3, default=True)


class IncrementLapResponse(messages.Message):
  """Response from incrementing lap count."""
  student_last_name = messages.StringField(1)
  student_first_name = messages.StringField(2)
  student_photo_url = messages.StringField(3)
  lap_count = messages.IntegerField(4)


# Create the RPC service that handles barcodes.
class BarcodesService(utils.CaminataService):
  """RPC service that handles barcodes."""

  @remote.method(IncrementLapRequest, IncrementLapResponse)
  def increment_lap_count(self, request):
    return IncrementLapResponse(student_last_name='Foo')


# Map the RPC service.
app = service.service_mappings([('/barcodes', BarcodesService)])
Esempio n. 24
0
from protorpc.wsgi import service

from REST import mpg_service

app = service.service_mappings([('/REST/mpg_service', mpg_service.PostService)])
Esempio n. 25
0
	location = messages.StringField(5, required=True)
	game_id = messages.StringField(6, required=True)
	score = messages.StringField(7)


class GamesRequest(messages.Message):
    team_id = messages.StringField(1, required=True)

# Create the response string
class GamesResponse(messages.Message):
    games = messages.MessageField(Games, 1, repeated=True)

# Create the RPC service to exchange messages
class GamesService(remote.Service):

    @remote.method(GamesRequest, GamesResponse)
    def games(self, request):
		t = Team()
		responseArray = []
		schedule = t.getGames(request.team_id)
		trimmedSchedule = schedule[10:len(schedule)-1]
		gamesArray = eval(trimmedSchedule)
		for game in gamesArray:
			logging.info(game)
			responseGame = Games(game_date=game['game_date'][5:], time=game['time'], home=game['home'], away=game['away'], location=game['location'], game_id=game['id'], score=game['score'])
			responseArray.append(responseGame)
		return GamesResponse(games=responseArray)

# Map the RPC service and path (/schedule)
app = service.service_mappings([('/games.*', GamesService)])
Esempio n. 26
0
class SeasonRequest(messages.Message):
    seasonRequest = messages.StringField(1, required=False)


# Create the response string
class SeasonResponse(messages.Message):
    seasons = messages.MessageField(Season, 1, repeated=True)


# Create the RPC service to exchange messages
class SeasonService(remote.Service):
    @remote.method(SeasonRequest, SeasonResponse)
    def season(self, request):
        theCache = memcache.get('seasons')
        if theCache is None:
            t = Team()
            seasons = []
            for team in t.getSeasons():
                season = Season(season=team.season)
                if season not in seasons:
                    seasons.append(season)
            if not memcache.add('seasons', seasons):
                logging.error('memcache failed to set')
            return SeasonResponse(seasons=seasons)
        else:
            return SeasonResponse(seasons=theCache)


# Map the RPC service and path (/schedule)
app = service.service_mappings([('/season.*', SeasonService)])
Esempio n. 27
0
            if problem.type == gemmate_model.Problem.FEASIBLE_HULL and problem.upper_bound > tree_bound:
                # create cyclic problem
                cyclic_problem_id = problem.hull + "_" + str(gemmate_model.Problem.CYCLIC)
                cyclic_problem = gemmate_model.Problem(hull=problem.hull, type=gemmate_model.Problem.CYCLIC,id=cyclic_problem_id,solved=False,parent=problem.key.parent())
    
                logging.info("Generating new CYCLIC problem with Id " + cyclic_problem_id)
                updated_problems_list.append(cyclic_problem)
            
            if problem.type == gemmate_model.Problem.CYCLIC and problem.upper_bound > tree_bound:
                # create regular problem
                regular_problem_id = problem.hull + "_" + str(gemmate_model.Problem.REGULAR)
                regular_problem = gemmate_model.Problem(hull=problem.hull, type=gemmate_model.Problem.REGULAR,id=regular_problem_id,solved=False,parent=problem.key.parent())
    
                logging.info("Generating new REGULAR problem with Id " + regular_problem_id)
                updated_problems_list.append(regular_problem)
        elif request.solution_type == "CUTOFF":
            problem.upper_bound = request.upper_bound
            problem.solution_type = "CUTOFF"
        else:
            problem.solution_type = "INFEASIBLE"

        updated_problems_list.append(problem)
            
        ndb.put_multi(updated_problems_list)
        
        return message_types.VoidMessage()

app = service.service_mappings([
    ('/ProblemDB.*', ProblemDB)
])
Esempio n. 28
0
# Create the response string
class SchoolResponse(messages.Message):
    schools = messages.MessageField(School, 1, repeated=True)


# Create the RPC service to exchange messages
class SchoolService(remote.Service):
    @remote.method(SchoolRequest, SchoolResponse)
    def school(self, request):
        cacheKey = request.season
        if cacheKey is None:
            cacheKey = 'AllSchools'
        theCache = memcache.get(cacheKey)
        if theCache is None:
            t = Team()
            schools = []
            for team in t.getSchools(request.season):
                school = School(school=team.school)
                if school not in schools:
                    schools.append(school)
            if not memcache.add(cacheKey, schools):
                logging.error('Unable to set cache')
            return SchoolResponse(schools=schools)
        else:
            return SchoolResponse(schools=theCache)


# Map the RPC service and path (/schedule)
app = service.service_mappings([('/school.*', SchoolService)])
Esempio n. 29
0
from protorpc import messages
from protorpc import remote
from protorpc.wsgi import service

package = 'hello'

# Create the request string containing the user's name
class HelloRequest(messages.Message):
    my_name = messages.StringField(1, required=True)

# Create the response string
class HelloResponse(messages.Message):
    hello = messages.StringField(1, required=True)

# Create the RPC service to exchange messages
class HelloService(remote.Service):

    @remote.method(HelloRequest, HelloResponse)
    def hello(self, request):
        return HelloResponse(hello='Hello there, %s!' % request.my_name)

# Map the RPC service and path (/hello)
app = service.service_mappings([('/hello.*', HelloService)])

class MovieFetcherRequest(messages.Message):  # pragma: no cover
    api_key = messages.StringField(1, required=True)
    omdb_start_id = messages.StringField(2, required=False)
    nof_movies = messages.IntegerField(3, required=False)


class MovieFetcherResponse(messages.Message):  # pragma: no cover
    result = messages.StringField(1, required=True)


class MovieFetcherService(remote.Service):  # pragma: no cover
    @remote.method(MovieFetcherRequest, MovieFetcherResponse)
    def fetch(self, request):
        # Use default start id if it is not supplied in the request
        start_id = request.omdb_start_id if request.omdb_start_id else DEFAULT_OMDB_ID
        # Use default number of movies if it is not supplied in the request
        nof_movies = request.nof_movies if request.nof_movies else DEFAULT_NOF_MOVIES

        moviefetcher = MovieFetcher()
        success = moviefetcher.get_movies_by_id(request.api_key, start_id,
                                                nof_movies)

        return MovieFetcherResponse(
            result=SUCCESS_MSG if success else FAILURE_MSG)


# Map the RPC service and path (/MovieFetcher.fetch)
app = service.service_mappings([('/MovieFetcher.*', MovieFetcherService)])
            return TBANSResponse(code=response.status_code, message=response.content)
        elif request.webhook:
            from tbans.models.requests.notifications.webhook_request import WebhookRequest
            webhook_request = WebhookRequest(notification, request.webhook.url, request.webhook.secret)
            logging.info('Ping - {}'.format(str(webhook_request)))

            response = webhook_request.send()
            logging.info('Ping Response - {}'.format(str(response)))
            return TBANSResponse(code=response.status_code, message=response.content)
        else:
            return self._application_error('Did not specify FCM or webhook to ping')

    @remote.method(VerificationRequest, VerificationResponse)
    def verification(self, request):
        """ Immediately dispatch a Verification to a webhook """
        self._validate_authentication()

        from tbans.models.notifications.verification import VerificationNotification
        notification = VerificationNotification(request.webhook.url, request.webhook.secret)

        from tbans.models.requests.notifications.webhook_request import WebhookRequest
        webhook_request = WebhookRequest(notification, request.webhook.url, request.webhook.secret)
        logging.info('Verification - {}'.format(str(webhook_request)))

        response = webhook_request.send()
        logging.info('Verification Response - {}'.format(str(response)))
        return VerificationResponse(code=response.status_code, message=response.content, verification_key=notification.verification_key)


app = service.service_mappings([('/tbans.*', TBANSService)])
Esempio n. 32
0
from protorpc.wsgi import service

import postservice

app = service.service_mappings([('/PostService', postservice.PostService)])
Esempio n. 33
0
    @remote.method(StartedEventMessage, StartedEventMessage)
    def delete(self, request):
        Key(urlsafe=request.id).delete()
        return request

    def transformStartedEventToEvent(self, startedEventMessage, endTime):
        self.delete(startedEventMessage)
        event = Event(
            actor=users.get_current_user(),
            activityCode=(startedEventMessage.activityCode),
            #comment = (startedEventMessage.comment),
            startTime=parseMsgTime(startedEventMessage.startTime),
            endTime=parseMsgTime(endTime),
            value=startedEventMessage.eventValue)
        event.put()
        return eventToMessage(event)

    @remote.method(CompleteStartedEventMessage, EventMessage)
    def complete(self, request):
        return ndb.transaction(lambda: self.transformStartedEventToEvent(
            request.startedEvent, request.endTime),
                               xg=True)


app = service.service_mappings([
    ('/service/event', EventService), ('/service/settings', SettingsService),
    ('/service/activity', ActivityService),
    ('/service/reportRequest', ReportRequestService),
    ('/service/startedEvents', StartedEventService)
])
Esempio n. 34
0
from protorpc.wsgi import service

import archiveservice

# Map the RPC service and path (/ArchiveService)
app = service.service_mappings([('/ArchiveService', archiveservice.ArchiveService)])
Esempio n. 35
0
'''
Created on Nov 12, 2014

@author: alantai
'''
from protorpc import messages, remote
from protorpc.wsgi import service

class MessageRequest(messages.Message):
    my_message = messages.StringField(1, required = True)
    
class MessageResponse(messages.Message):
    my_response = messages.StringField(1, required = True)
    
class MessageService(remote.Service):
    @remote.method(MessageRequest, MessageResponse)
    def handle_message(self, request):
        return MessageResponse( my_message = "The message is: {my_message}".format("my_message", request.my_message))
    
app = service.service_mappings([('/protortc/message_service/test', MessageService)])
Esempio n. 36
0
# Create the request string containing the user's name
class CoachRequest(messages.Message):
	school = messages.StringField(1, required=False)
	season = messages.StringField(2, required=False)

# Create the RPC service to exchange messages
class CoachService(remote.Service):

	@remote.method(CoachRequest, Coaches)
	def coach(self, request):
		cacheKey = 'AllCoaches'
		if (request.school is not None) and (request.season is None):
			cacheKey = request.school
		else:
			cacheKey = request.season + request.school
		theCache = memcache.get(cacheKey)
		if theCache is None:
			t = Team()
			coaches = []
			for team in t.getCoaches(request.school, request.season):
				coach = Coach(team_id=team.teamId, name=team.coach, school=team.school, grade=team.grade)
				coaches.append(coach)
			if not memcache.add(cacheKey, coaches):
				logging.error('Unable to set cache')
			return Coaches(coaches=coaches)
		else:
			return Coaches(coaches=theCache)

# Map the RPC service and path (/schedule)
app = service.service_mappings([('/coach.*', CoachService)])
Esempio n. 37
0
    season = messages.StringField(1, required=False)

# Create the response string
class SchoolResponse(messages.Message):
	schools = messages.MessageField(School, 1, repeated=True)

# Create the RPC service to exchange messages
class SchoolService(remote.Service):

 	@remote.method(SchoolRequest, SchoolResponse)
 	def school(self, request):
		cacheKey = request.season
		if cacheKey is None:
			cacheKey = 'AllSchools'
		theCache = memcache.get(cacheKey)
		if theCache is None:
			t = Team()
			schools = []
			for team in t.getSchools(request.season):
				school = School(school=team.school)
				if school not in schools:
					schools.append(school)
			if not memcache.add(cacheKey, schools):
				logging.error('Unable to set cache')
			return SchoolResponse(schools=schools)
		else:
			return SchoolResponse(schools=theCache)

# Map the RPC service and path (/schedule)
app = service.service_mappings([('/school.*', SchoolService)])
Esempio n. 38
0
#!/usr/bin/python

try:
  from grow import submodules
  submodules.fix_imports()
except ImportError:
  pass

import webapp2
from protorpc.wsgi import service
from grow.server import handlers
from grow.server import services


podserver_app = webapp2.WSGIApplication([
    ('/.*', handlers.PodHandler),
])
routes = [
    ('/_api/pods.*', services.PodService),
]
application = service.service_mappings(
    routes,
    service_prefix='/_api',
    registry_path='/_api/protorpc',
    append_wsgi_apps=[podserver_app])
Esempio n. 39
0
# -*- coding: UTF-8 -*-

import logging
logger = logging.getLogger(__name__)
import traceback

from protorpc.wsgi import service
from protorpc.webapp import forms

from . import test_service
from . import playswith_page_service
from . import project_service

package = "org.angularjs.playswith"

mapping = [
    ("/rpc/test", test_service.TestService),
    ("/rpc/project", project_service.ProjectService),
    ("/rpc/playswith_page", playswith_page_service.PlayswithPageService),
    ]

app = service.service_mappings(mapping, registry_path="/protorpc")
Esempio n. 40
0
    def delete(self, request):
        Key(urlsafe = request.id).delete()
        return request


    def transformStartedEventToEvent(self, startedEventMessage, endTime):
        self.delete(startedEventMessage)
        event = Event(
                actor = users.get_current_user(),
                activityCode = (startedEventMessage.activityCode),
                #comment = (startedEventMessage.comment),
                startTime = parseMsgTime(startedEventMessage.startTime), endTime = parseMsgTime(endTime),
                value = startedEventMessage.eventValue)
        event.put()
        return eventToMessage(event)

    @remote.method(CompleteStartedEventMessage, EventMessage)
    def complete(self, request):
        return ndb.transaction(lambda : self.transformStartedEventToEvent(request.startedEvent, request.endTime), xg=True)






app = service.service_mappings(
    [('/service/event', EventService),
     ('/service/settings', SettingsService),
     ('/service/activity', ActivityService),
     ('/service/reportRequest', ReportRequestService),
     ('/service/startedEvents', StartedEventService)])
Esempio n. 41
0
auth_app = webapp2.WSGIApplication([
#    ('/auth/signin/start', auth_handlers.SignInHandler),
#    ('/auth/signin/callback', auth_handlers.SignInCallbackHandler),
#    ('/auth/sign_in', auth_handlers.SignInHandler),
], config=config.WEBAPP2_AUTH_CONFIG)

oauth2_app = webapp2.WSGIApplication([
    ('/oauth2callback', auth_handlers.OAuth2CallbackHandler),
], config=config.WEBAPP2_AUTH_CONFIG)

api_app = service.service_mappings((
    ('/_api/avatars.*', avatar_services.AvatarService),
    ('/_api/filesets.*', fileset_services.FilesetService),
    ('/_api/me.*', user_services.MeService),
    ('/_api/owners.*', owner_services.OwnerService),
    ('/_api/orgs.*', org_services.OrgService),
    ('/_api/projects.*', project_services.ProjectService),
    ('/_api/teams.*', team_services.TeamService),
    ('/_api/users.*', user_services.UserService),
), registry_path='/_api/protorpc')


def domain_middleware(conditions_and_apps):
  def middleware(environ, start_response):
    for condition_func, app in conditions_and_apps:
      if condition_func(environ['SERVER_NAME'], path=environ['PATH_INFO']):
        return app(environ, start_response)
  return middleware


def allowed_user_domains_middleware(app):
Esempio n. 42
0
    @remote.method(OrganizationPayload, OrganizationPayload)
    def get(self, message):
        """Get organization."""
        props = dict()
        return OrganizationPayload(**props)

    @remote.method(PagePayload, PagePayload)
    def page(self, message):
        """Return page of organizations."""
        curs = None
        if message.cursor:
            curs = Cursor(urlsafe=message.cursor)
        page, next, more = Organization.page(message.limit, cursor=curs, 
            format='message')        
        return page

class OrganizationAsync(webapp2.RequestHandler):
    """Async organization handler for taskqueue def."""

    def post(self):
        """Dispatches incoming task job.""" 
        pass

# RPC service endpoint.
rpc = service.service_mappings([('/service/organization', OrganizationRPC),],)

# Taskqueue endpoint for async services.
handler = webapp2.WSGIApplication([
    ('/api/async/organization', OrganizationAsync),], debug=True)
Esempio n. 43
0
        return GetMovieListResponse(result=movie_titles)

    # Deletes a movie my omdb id
    @remote.method(DeleteMovieRequest, DeleteMovieResponse)
    def delete_movie(self, request):
        q = db_movie.Movie.query()
        movie = q.filter(db_movie.Movie.omdb_id == request.omdb_id).get()

        if movie:
            movie.key.delete()

        return DeleteMovieResponse(
            result=DELETE_MOVIE_SUCCESS_MSG %
            request.omdb_id if movie else DELETE_MOVIE_FAILURE_MSG %
            request.omdb_id)

    # Adds a movie by title
    @remote.method(AddMovieRequest, AddMovieResponse)
    def add_movie(self, request):
        moviefetcher = MovieFetcher()
        success = moviefetcher.get_movie_by_title(request.api_key,
                                                  request.title)
        return AddMovieResponse(
            result=ADD_MOVIE_SUCCESS_MSG %
            request.title if success else ADD_MOVIE_FAILURE_MSG %
            request.title)


# Map the RPC service and path (/api)
app = service.service_mappings([('/api.*', ApiService)])
Esempio n. 44
0
from protorpc.wsgi import service as wsgi_service

import businesspageforms_service
import feedbackpageforms_service

service = wsgi_service.service_mappings([
    ('/forms/businesspage', businesspageforms_service.PostService),
    ('/forms/feedbackpage', feedbackpageforms_service.PostService)
])
Esempio n. 45
0
from . import handlers
from products import services as product_services
from protorpc.wsgi import service
import webapp2


app = webapp2.WSGIApplication((
    ('/', handlers.MainHandler),
))

api_app = service.service_mappings((
   ('/_api/products.*', product_services.ProductService),
))
Esempio n. 46
0
__author__ = 'aparbane'

from web.joinhour.services.companion_ship_rating_service import CompanionShipRatingService
from protorpc.wsgi import service

app = service.service_mappings([('/companion_ship_rating_service',
                                 CompanionShipRatingService)])
Esempio n. 47
0
    ('/_grow/access-requests/approve/(.*)', access_requests.ApproveAccessRequestHandler),
    ('/_grow/access-requests/process', access_requests.ProcessHandler),
    ('/_grow/access-requests', access_requests.ManageAccessHandler),
    ('/_grow/users/csv', access_requests.DownloadCsvHandler),
    ('/_grow/users/import', access_requests.ImportFromSheetsHandler),
    ('/_grow/users/(.*)', access_requests.ManageUserHandler),
    ('/_grow/users', access_requests.ManageUsersHandler),
    ('/_grow/protected/cache-sheets', protected_middleware.CacheSheetsHandler),
    ('/_grow/search/index', search_app.IndexHandler),
    ('/_ah/warmup', search_app.IndexHandler),
], config=build_server_config)

root = build_server_config['root']
locales = build_server_config['locales']
default_locale = build_server_config['default_locale']
static_paths = build_server_config['static_paths']

_static_app = StaticFileServerApplication(root=root)
_locale_app = LocaleRedirectMiddleware(
        _static_app, root=root, locales=locales,
        default_locale=default_locale)
_protected_app = protected_middleware.ProtectedMiddleware(_locale_app, config=build_server_config)
app = SheetsAuthMiddleware(
        _protected_app, static_paths=static_paths,
        config=build_server_config)

api = cors.CorsMiddleware(service.service_mappings([
    ('/_grow/api/users.*', users.UsersService),
    ('/_grow/api/search.*', search_app.SearchService),
]))
Esempio n. 48
0
    Returns:
      An updated ChecklistITemMessageUpdate message.
    """
        item = ndb.Key(urlsafe=request.checklist_item.key).get()
        if item:
            item.FromRpcMessage(request.checklist_item)
            item.put()
            request.checklist_item = item.ToRpcMessage()
            return request

    @remote.method(message_types.VoidMessage, protorpc_messages.ChecklistItems)
    def GetAllItems(self, request):
        """Gets all items from the datastore with a limit of 1000 items.

    Args:
      request; VoidMessage: A VoidMessage instance.

    Returns:
      A populated ChecklistItems ProtoRPC response message.
    """
        response = protorpc_messages.ChecklistItems()
        query = models.ChecklistItem().query()
        response.checklist_items = [
            item.ToRpcMessage() for item in query.fetch(limit=1000)
        ]
        return response


app = service.service_mappings([('/ChecklistService', ChecklistService)])
Esempio n. 49
0

# Create the RPC service to exchange messages
class CoachService(remote.Service):
    @remote.method(CoachRequest, Coaches)
    def coach(self, request):
        cacheKey = 'AllCoaches'
        if (request.school is not None) and (request.season is None):
            cacheKey = request.school
        else:
            cacheKey = request.season + request.school
        theCache = memcache.get(cacheKey)
        if theCache is None:
            t = Team()
            coaches = []
            for team in t.getCoaches(request.school, request.season):
                coach = Coach(team_id=team.teamId,
                              name=team.coach,
                              school=team.school,
                              grade=team.grade)
                coaches.append(coach)
            if not memcache.add(cacheKey, coaches):
                logging.error('Unable to set cache')
            return Coaches(coaches=coaches)
        else:
            return Coaches(coaches=theCache)


# Map the RPC service and path (/schedule)
app = service.service_mappings([('/coach.*', CoachService)])
Esempio n. 50
0
                type = 'query'
                query_count = count
            else:
                type = 'query-view'
                query_count = limit
            params = dict(query=keywords, type=type, count=query_count, latlon=self.cityLatLong, res_counts=json.dumps(res_counts))
            taskqueue.add(url='/apitracker', params=params, queue_name="apitracker")
        else:
            error = result[0].__class__.__name__
            params = dict(error=error, query=keywords, type='query', latlon=self.cityLatLong)
            taskqueue.add(url='/apitracker', params=params, queue_name="apitracker")
            response = RecordList(error=unicode(error))
            return response

        if cursor:
            cursor = cursor.web_safe_string

        items = [RecordPayload(id=x['keyname'], json=json.dumps(x)) \
            for x in recs if x]

        response = RecordList(items=items, cursor=cursor, count=count)

        return response

    @remote.method(RecordList, RecordList)
    def count(self, message):
        q = json.loads(message.q)
        return RecordList(count=RecordIndex.search(q, None, count=True))
         
rpc = service.service_mappings([('/service/rpc/record', RecordService),],)
	away = messages.StringField(4, required=True)
	location = messages.StringField(5, required=True)
	game_id = messages.StringField(6, required=True)
	score = messages.StringField(7)


class GamesMultiTeamRequest(messages.Message):
    team_ids = messages.StringField(1, required=True)

# Create the response string
class GamesMultiTeamResponse(messages.Message):
    games = messages.MessageField(Games, 1, repeated=True)

# Create the RPC service to exchange messages
class GamesMultiTeamService(remote.Service):

    @remote.method(GamesMultiTeamRequest, GamesMultiTeamResponse)
    def games(self, request):
		t = Team()
		responseArray = []
		schedule = t.getGamesMultiTeams(request.team_ids)
		gamesArray = eval(schedule)
		for game in gamesArray:
			logging.info(game)
			responseGame = Games(game_date=game['game_date'][5:], time=game['time'], home=game['home'], away=game['away'], location=game['location'], game_id=game['id'], score=game['score'])
			responseArray.append(responseGame)
		return GamesMultiTeamResponse(games=responseArray)

# Map the RPC service and path (/schedule)
app = service.service_mappings([('/multigames.*', GamesMultiTeamService)])
Esempio n. 52
0
from protorpc import messages
from protorpc import remote
from protorpc.wsgi import service
from team import Team
import logging

package = 'SaintsSchedule'

class ScheduleRequest(messages.Message):
    team_id = messages.StringField(1, required=True)

# Create the response string
class ScheduleResponse(messages.Message):
    schedule = messages.StringField(1, required=True)

# Create the RPC service to exchange messages
class ScheduleService(remote.Service):

    @remote.method(ScheduleRequest, ScheduleResponse)
    def schedule(self, request):
		t = Team()
		games = t.getGames(request.team_id)
		logging.info("games = " + games)
		return ScheduleResponse(schedule=games)

# Map the RPC service and path (/schedule)
app = service.service_mappings([('/schedule.*', ScheduleService)])
Esempio n. 53
0
from protorpc import messages
from protorpc import remote
from protorpc.wsgi import service

package = 'hello'


# Create the request string containing the user's name
class HelloRequest(messages.Message):
    my_name = messages.StringField(1, required=True)


# Create the response string
class HelloResponse(messages.Message):
    hello = messages.StringField(1, required=True)


# Create the RPC service to exchange messages
class HelloService(remote.Service):
    @remote.method(HelloRequest, HelloResponse)
    def hello(self, request):
        return HelloResponse(hello='Hello there, %s!' % request.my_name)


# Map the RPC service and path (/hello)
app = service.service_mappings([('/hello.*', HelloService)])
Esempio n. 54
0
            logging.info('Ping Response - {}'.format(str(response)))
            return TBANSResponse(code=response.status_code,
                                 message=response.content)
        else:
            return self._application_error(
                'Did not specify FCM or webhook to ping')

    @remote.method(VerificationRequest, VerificationResponse)
    def verification(self, request):
        """ Immediately dispatch a Verification to a webhook """
        self._validate_authentication()

        from tbans.models.notifications.verification import VerificationNotification
        notification = VerificationNotification(request.webhook.url,
                                                request.webhook.secret)

        from tbans.models.requests.notifications.webhook_request import WebhookRequest
        webhook_request = WebhookRequest(notification, request.webhook.url,
                                         request.webhook.secret)
        logging.info('Verification - {}'.format(str(webhook_request)))

        response = webhook_request.send()
        logging.info('Verification Response - {}'.format(str(response)))
        return VerificationResponse(
            code=response.status_code,
            message=response.content,
            verification_key=notification.verification_key)


app = service.service_mappings([('/tbans.*', TBANSService)])
Esempio n. 55
0
import appengine_config

from . import services
from protorpc.wsgi import service

api_app = service.service_mappings((
    ('/_api/campaigns.*', services.CampaignService),
    ('/_api/orders.*', services.OrderService),
))