Beispiel #1
0
def get_api():
  import endpoints
  api_services = list()
  for api in config.API:
    module = webapp2.import_string(api)
    api_services.extend(module.api_services)
  return endpoints.api_server(api_services)
 def test_make_move_made_match(self, mock_taskqueue):
     """Functional test for api call to make a move"""
     #create the api 
     api_call = '/_ah/spi/GameApi.make_move'
     app = endpoints.api_server([GameApi], restricted=False)
     testapp = webtest.TestApp(app)
     
     #create a new game with a mock gridboard
     (game, first_user, second_user) = self._get_new_game_with_mock_gridboard()
       
     #make the first move, flip DEATH. Test first guess made.  
     #the expected request object as a dictionary, to be serialised to JSON by webtest
     request = {"urlsafe_game_key":game.key.urlsafe(), "name":first_user.name,  "row":0, "column":0} 
     resp = testapp.post_json(api_call, request)
     self.assertEqual(resp.json['message'], "One more guess to make")
       
     #test card is flipped
     self.assertTrue(game.board[0][0].flipped)
     
     #make the second move, flip DEATH. Test match is made.
     request = {"urlsafe_game_key":game.key.urlsafe(), "name":first_user.name,  "row":0, "column":2} 
     resp = testapp.post_json(api_call, request)
     self.assertEqual(resp.json['message'], "You made a match")  
     self.assertTrue(game.board[0][2].flipped)
     self.assertTrue(resp.json['history'], "[good golly:DEATH:0:0:DEATH:0:2:True]")    
     
     #test game history with two moves
     request = {"urlsafe_game_key":game.key.urlsafe(), "name":first_user.name,  "row":3, "column":3} 
     resp = testapp.post_json(api_call, request)
     request = {"urlsafe_game_key":game.key.urlsafe(), "name":first_user.name,  "row":3, "column":2} 
     resp = testapp.post_json(api_call, request)
     self.assertEqual(resp.json['history'], "[good golly:DEATH:0:0:DEATH:0:2:True, good golly:HERMIT:3:3:TEMPERANCE:3:2:False]")  
 def test_get_user_scores(self):
     """Functional test for api call to retrieve user scores"""
     #create the api 
     api_call = '/_ah/spi/GameApi.get_user_scores'
     app = endpoints.api_server([GameApi], restricted=False)
     testapp = webtest.TestApp(app)
     
     #create some scores
     player_one, player_two = self._get_two_players()
     scores.new_score(winner=player_one.key, loser=player_two.key, first_user_score=3, second_user_score=2)
     
     #test user not found
     request = {"name":"asdfsdf"} 
     self.assertRaises(Exception, testapp.post_json, api_call, request)
    
     #test scores retrieved
     request = {"name":player_one.name} 
     resp = testapp.post_json(api_call, request)
     
     self.assertEqual(len(resp.json['items']), 1)
     self.assertEquals(resp.json['items'][0]['winner'], player_one.name)
     self.assertEquals(resp.json['items'][0]['winner_score'], "3")
     self.assertEquals(resp.json['items'][0]['loser'], player_two.name)
     self.assertEquals(resp.json['items'][0]['loser_score'], "2")
     
     request = {"name":player_two.name} 
     resp = testapp.post_json(api_call, request)
     
     self.assertEqual(len(resp.json['items']), 1)
     self.assertEquals(resp.json['items'][0]['winner'], player_one.name)
     self.assertEquals(resp.json['items'][0]['winner_score'], "3")
     self.assertEquals(resp.json['items'][0]['loser'], player_two.name)
     self.assertEquals(resp.json['items'][0]['loser_score'], "2")
 def test_new_game(self):
     """Functional test for api call to get a new game"""
     #create the api 
     api_call = '/_ah/spi/GameApi.new_game'
     app = endpoints.api_server([GameApi], restricted=False)
     testapp = webtest.TestApp(app)
     
     #create two players
     first_user, second_user = self._get_two_players() 
   
     #the expected request object as a dictionary, to be serialised to JSON by webtest
     request = {"first_user":first_user.name, "second_user":second_user.name} 
     resp = testapp.post_json(api_call, request)
     
     #check correct default values have been created
     self.assertEqual(resp.json['next_move'], first_user.name)
     self.assertEqual(resp.json['game_over'], False)
     self.assertEqual(resp.json['unmatched_pairs'], "8")
     self.assertEqual(resp.json['first_user_score'], "0")
     self.assertEqual(resp.json['second_user_score'], "0")
     self.assertEqual(resp.json['history'], "[]")
     
     #test user not found
     request = {"first_user":"", "second_user":""} 
     self.assertRaises(Exception, testapp.post_json, api_call, request)
     
     #test calling new game with the same user twice
     request = {"first_user":first_user.name, "second_user":first_user.name} 
     self.assertRaises(Exception, testapp.post_json, api_call, request)
 def test_get_user_rankings(self):
     """Test that you are able to retrieve a list of all users ranked by win percentage"""
      
     api_call = '/_ah/spi/UserApi.get_user_rankings'
     app = endpoints.api_server([UserApi], restricted=False)
     testapp = webtest.TestApp(app)
      
     user = User(name=u'no win', email=u'*****@*****.**')
     user.put()
      
     userone = User(name=u'one win', email=u'*****@*****.**', total_played=1, wins=1)
     userone.put()
      
     usertwo = User(name=u'two wins', email=u'*****@*****.**', total_played=2, wins=1)
     usertwo.put()
      
     #the expected request object as a dictionary, to be serialised to JSON by webtest
     resp = testapp.post_json(api_call)
       
     self.assertEqual(len(resp.json['items']), 2)
     self.assertEquals(resp.json['items'][1]['name'], usertwo.name)
     self.assertEquals(resp.json['items'][1]['email'], "*****@*****.**")
     self.assertEquals(resp.json['items'][1]['wins'], "1")
     self.assertEquals(resp.json['items'][1]['total_played'], "2")
     self.assertEquals(resp.json['items'][1]['win_percentage'], 0.5)
     self.assertEquals(resp.json['items'][0]['name'], userone.name)
     self.assertEquals(resp.json['items'][0]['email'], "*****@*****.**")
     self.assertEquals(resp.json['items'][0]['wins'], "1")
     self.assertEquals(resp.json['items'][0]['total_played'], "1")
     self.assertEquals(resp.json['items'][0]['win_percentage'], 1)
Beispiel #6
0
def create_application():
    ereporter2.register_formatter()
    # App that serves HTML pages and old API.
    a = handlers_frontend.create_application(False)
    # App that serves new endpoints API.
    api = endpoints.api_server([handlers_endpoints.swarming_api])
    return a, api
Beispiel #7
0
 def api_app(self):
   """Returns instance of webtest.TestApp that wraps Endpoints API service."""
   if self._api_app is None:
     self._api_app = webtest.TestApp(
         endpoints.api_server([self.api_service_cls], restricted=False),
         extra_environ={'REMOTE_ADDR': '127.0.0.1'})
   return self._api_app
Beispiel #8
0
def create_applications():
  ereporter2.register_formatter()

  # App that serves HTML pages and old API.
  frontend = handlers_frontend.create_application(False)
  # App that serves endpoints APIs.
  api = endpoints.api_server([auth.AuthService, config.ConfigApi])
  return frontend, api
Beispiel #9
0
def create_endpoints_app():
  """Returns WSGI app that serves cloud endpoints requests."""
  apis = [
    admin.AdminApi,
    cas.CASServiceApi,
    cipd.PackageRepositoryApi,
  ]
  return endpoints.api_server(apis, restricted=not utils.is_local_dev_server())
Beispiel #10
0
def create_application():
    ereporter2.register_formatter()

    # App that serves HTML pages and old API.
    frontend = handlers_frontend.create_application(False)
    # App that serves new endpoints API.
    api = endpoints.api_server([handlers_endpoints_v1.IsolateService, handlers_endpoints_v2.IsolateServiceV2])
    return frontend, api
Beispiel #11
0
 def testapp(self):
     """
     Get the testapp created from the added endpoint services. Typically it's not necessary
     to access this directly, instead, you would use :func:`invoke`.
     """
     if not self._testapp:
         import endpoints
         api_server = endpoints.api_server(self._services, restricted=False)
         self._testapp = webtest.TestApp(api_server)
     return self._testapp
    def setUp(self):

        # Call super method
        super(SupplierTestCase, self).setUp()

        #  Create service
        supplierService = endpoints.api_server(
            [SupplierService], restricted=False)

        # Create test
        self.testapp = webtest.TestApp(supplierService)
    def setUp(self):

        # Call super method
        super(ProductTestCase, self).setUp()

        #  Create service
        productService = endpoints.api_server(
            [ProductService], restricted=False)

        # Create test
        self.testapp = webtest.TestApp(productService)
def _make_app(api_use, method_use):
    @endpoints.api(name='filefetcher', version='1.0.0', use_request_uri=api_use)
    class FileFetcherApi(remote.Service):
        @endpoints.method(FILE_RESOURCE, FileResponse, path='get_file/{path}',
                          http_method='GET', name='get_file', use_request_uri=method_use)
        def get_file(self, request):
            if request.path not in FILES:
                raise endpoints.NotFoundException()
            val = FileResponse(path=request.path, payload=FILES[request.path])
            return val
    return webtest.TestApp(endpoints.api_server([FileFetcherApi]), lint=False)
 def setUp(self):
     self.testbed = testbed.Testbed()
     self.testbed.setup_env(
             current_version_id='testbed.version',
             USER_EMAIL='test-user-1',
             overwrite=True)
     #needed because endpoints expects a . in this value
     self.testbed.activate()
     self.testbed.init_datastore_v3_stub()
     self.testbed.init_memcache_stub()
     self.app = endpoints.api_server([api.PocketMonApi], restricted=False)
     self.testapp = webtest.TestApp(self.app)
Beispiel #16
0
  def setUp(self):  # pylint: disable=E1002
    super(ApiTest, self).setUp()
    # restricted=False is needed for testing.
    # Initialized here because setUp() has to be run first.
    self.app_module = endpoints.api_server(
        [trooper_o_api.TrooperOMaticAPI],
        restricted=False
    )

    testing_common.StubUrlfetch(test_data.URLFETCH_RESPONSES,
                                stub=self.testbed.get_stub('urlfetch'))

    cron.datetime_now = MockNow
Beispiel #17
0
    def setUp(self):
        from google.appengine.datastore import datastore_stub_util
        
        app = endpoints.api_server([main.Api], restricted=False)
        self.testapp = webtest.TestApp(app)
        self.testbed = testbed.Testbed()
        
        self.testbed.setup_env(current_version_id='testbed.version') #needed because endpoints expects a . in this value
        self.policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(probability=1)

        self.testbed.activate()        
        self.testbed.init_datastore_v3_stub(consistency_policy=self.policy)
        self.testbed.init_memcache_stub(True)
Beispiel #18
0
  def __init__(self, *argv, **kwargv):
    super(TestCase, self).__init__(*argv, **kwargv)

    if isinstance(self.application, endpoints.api_config._ApiDecorator):
      api_names = list()
      for api_class in self.application.get_api_classes():
        for name, _method in api_class.all_remote_methods().items():
          api_names.append(name)
      self.api_names = tuple(api_names)
      self.application = endpoints.api_server([self.application], restricted=False)
      self.is_endpoints = True
    else:
      self.api_names = tuple()
Beispiel #19
0
def create_application():
  ereporter2.register_formatter()

  # App that serves HTML pages and old API.
  frontend = handlers_frontend.create_application(False)

  def is_enabled_callback():
    return config.settings().enable_ts_monitoring

  gae_ts_mon.initialize(frontend, is_enabled_fn=is_enabled_callback)
  # App that serves new endpoints API.
  api = endpoints.api_server([handlers_endpoints_v1.IsolateService])
  return frontend, api
 def setUp(self):
   app = endpoints.api_server([AttendanceAPI], restricted=False)
   self.testapp = webtest.TestApp(app)
   self.testbed = testbed.Testbed()
   self.testbed.activate()
   self.testbed.init_datastore_v3_stub()
   self.testbed.init_user_stub()
   self.testbed.init_memcache_stub()
   self.testbed.setup_env(
     USER_EMAIL = '*****@*****.**',
     USER_ID = '123',
     USER_IS_ADMIN = '1',
     overwrite = True,
     current_version_id='testbed.version')
   self.createClassAndStudents()
 def test_make_move_game_already_over(self, mock_taskqueue):
     """Functional test for api call to make a move"""
     #create the api 
     api_call = '/_ah/spi/GameApi.make_move'
     app = endpoints.api_server([GameApi], restricted=False)
     testapp = webtest.TestApp(app)
     
     #create a new game with a mock gridboard
     (game, first_user, second_user) = self._get_new_game_with_mock_gridboard()
 
     game.game_over = True
     game.put()
     
     #test game already over
     request = {"urlsafe_game_key":game.key.urlsafe(), "name":first_user.name,  "row":0, "column":1} 
     self.assertRaises(Exception, testapp.post_json, api_call, request)
Beispiel #22
0
def create_application():
  ereporter2.register_formatter()

  def is_enabled_callback():
    return config.settings().enable_ts_monitoring

  # App that serves HTML pages and old API.
  frontend_app = handlers_frontend.create_application(False)
  gae_ts_mon.initialize(frontend_app, is_enabled_fn=is_enabled_callback)
  # Local import, because it instantiates the mapreduce app.
  from mapreduce import main
  gae_ts_mon.initialize(main.APP, is_enabled_fn=is_enabled_callback)
  api = endpoints.api_server([
    handlers_endpoints.swarming_api,
    # components.config endpoints for validation and configuring of luci-config
    # service URL.
    config.ConfigApi,
  ])
  ts_mon_metrics.initialize()
  return frontend_app, api, main.APP
 def test_make_move_invalid_move(self, mock_taskqueue):
     """Functional test for api call to make a move"""
     #create the api 
     api_call = '/_ah/spi/GameApi.make_move'
     app = endpoints.api_server([GameApi], restricted=False)
     testapp = webtest.TestApp(app)
     
     #create a new game with a mock gridboard
     (game, first_user, second_user) = self._get_new_game_with_mock_gridboard()
    
     #test exception raised if exceed gridboard boundary
     request = {"urlsafe_game_key":game.key.urlsafe(), "name":first_user.name,  "row":0, "column":-1} 
     self.assertRaises(Exception, testapp.post_json, api_call, request)
     request = {"urlsafe_game_key":game.key.urlsafe(), "name":first_user.name,  "row":4, "column":0} 
     self.assertRaises(Exception, testapp.post_json, api_call, request)
    
     game.board[0][0].flip()
    
     #test exception raised if card already flipped
     request = {"urlsafe_game_key":game.key.urlsafe(), "name":first_user.name,  "row":0, "column":0} 
     self.assertRaises(Exception, testapp.post_json, api_call, request)
 def test_get_game(self):
     """Functional test for api call to get an existing game"""
     #create the api 
     api_call = '/_ah/spi/GameApi.get_game'
     app = endpoints.api_server([GameApi], restricted=False)
     testapp = webtest.TestApp(app)
     
     #create two players
     game, first_user, second_user = self._get_new_game() 
   
     #the expected request object as a dictionary, to be serialised to JSON by webtest
     request = {"urlsafe_game_key":game.key.urlsafe()} 
     resp = testapp.post_json(api_call, request)
     
     #check correct default values have been created
     self.assertEqual(resp.json['next_move'], first_user.name)
     self.assertEqual(resp.json['game_over'], False)
     self.assertEqual(resp.json['unmatched_pairs'], "8")
     self.assertEqual(resp.json['first_user_score'], "0")
     self.assertEqual(resp.json['second_user_score'], "0")
     self.assertEqual(resp.json['history'], "[]")
Beispiel #25
0
            win_percentage = (float(len(wins)) /
                              (len(wins) + len(loses))) * 100
            avg_moves = 0
            for score in scores:
                avg_moves += score.moves
            avg_moves = avg_moves / (len(wins) + len(loses))
            user_ratings.append([user_name, win_percentage, avg_moves])
        user_ratings = sorted(user_ratings, key=lambda x: (-x[1], x[2]))
        messages = []
        for rating in user_ratings:
            message = 'Name: ' + rating[0] + ', Win rating: '
            message += '{0:.2f}%, Average Moves: '.format(rating[1])
            message += str(rating[2])
            messages.append(message)
        return StringMessages(items=[m for m in messages])

    @endpoints.method(request_message=GET_GAME_REQUEST,
                      response_message=GameHistoryForm,
                      path='game/{urlsafe_game_key}/history',
                      name='get_game_history',
                      http_method='GET')
    def get_game_history(self, request):
        """Returns a play-by-play history of a given game"""
        game = get_by_urlsafe(request.urlsafe_game_key, Game)
        if not game:
            raise endpoints.NotFoundException('Game not found')
        return game.return_history()


api = endpoints.api_server([BattleshipAPI])
          new_song = Song(track_id = request.track_id, user_suggest = user_query.get(keys_only=True),party_key = user.party_key,played = False)
          new_song.put()
          return add_response(response='Added song as a suggestion')
      else:
          new_activity = Activity(song=song_query.get(keys_only=True),party_key=user.party_key,user_vote=user_query.get(keys_only=True))
          new_activity.put()
          return add_response(response='Song already added as suggestion will consider this as a vote')

  @endpoints.method(Song_class,add_response,
                    path='authed_voteSong',http_method="POST",
                    name='pocketjuke.voteSongAuthed')
  def vote_song(self,request):

      current_user = endpoints.get_current_user()
      user_query = User.query(User.user_id == current_user.user_id())
      user = user_query.get()
      song_query = Song.query(ndb.AND(Song.track_id == request.track_id,Song.party_key == user.party_key))
      if song_query.get():

          new_activity = Activity(song=song_query.get(keys_only=True),party_key = user.party_key,user_vote=user_query.get(keys_only=True))
          new_activity.put()
          return add_response(response='Added vote to activity list')
      else:
          return add_response(response = 'Could not added vote to activity list')





APPLICATION = endpoints.api_server([PocketJukeAPI])
Beispiel #27
0
        user.put()
        friend.put()

        return message_types.VoidMessage()

    @endpoints.method(token_uid_request,
                      message_types.VoidMessage,
                      path='friend/{uid}/unfriend',
                      http_method='GET',
                      name='friends.unfriend')
    def unfriend(self, request):
        user = self.get_user_from_token(request.token)
        if not user:
            raise endpoints.UnauthorizedException('UNAUTHORIZED')

        key = ndb.Key(Account, int(request.uid))
        friend = key.get()

        if friend is None:
            raise endpoints.NotFoundException('FRIEND_NOT_FOUND')

        user.friends.remove(key)
        user.put()
        friend.friends.remove(user.key)
        friend.put()

        return message_types.VoidMessage()


APPLICATION = endpoints.api_server([ChessApi])
Beispiel #28
0
        except committers.AuthorizationError as e:
            # Technically should be 403, but use 404 to avoid exposing list names.
            logging.warning('Request not authorized: %s', e.message)
            self.abort(404)
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.write('\n'.join(sorted(l.emails)))


class UpdateHandler(webapp2.RequestHandler):
    @hmac_util.CheckHmacAuth
    @auth_util.RequireAuth
    def post(self, list_name):
        """Updates the list of committers from the POST data recieved."""
        user = auth_util.User.from_request(self.request)
        email_json = base64.b64decode(self.request.get('committers'))
        emails = json.loads(email_json)

        # Throws committers.AuthorizationError if not HMAC authenticated, but we
        # require that via the decorator.
        committers.put_list(user, list_name, emails)


app = webapp2.WSGIApplication([
    ('/', MainPageHandler),
    ('/lists/([a-zA-Z0-9.@_-]+)', ListHandler),
    ('/update/([a-zA-Z0-9.@_-]+)', UpdateHandler),
],
                              debug=True)

ep_server = endpoints.api_server([ep_api.CommittersApi])
            checklist_items.append(
                models.CheckListItem(title=item.title, checked=item.checked))
        note.checklist_items = checklist_items

        files = []
        for file_id in request.files:
            try:
                files.append(ndb.Key(urlsafe=file_id).get())
            except TypeError:
                continue
        note.files = files
        note.put()
        return resources.NoteRepr(key=request.key,
                                  title=request.title,
                                  content=request.content,
                                  date_created=request.date_created,
                                  checklist_items=request.checklist_items,
                                  files=request.files)

    @endpoints.method(NoteRequestContainer,
                      message_types.VoidMessage,
                      path='notes/{key}',
                      http_method='DELETE',
                      name='notes.notesDelete')
    def note_delete(self, request):
        ndb.Key(urlsafe=request.key).delete()
        return message_types.VoidMessage()


app = endpoints.api_server([NotesApi])
Beispiel #30
0
      WhoResponse,
      name='who',
      http_method='GET')
  @auth.public
  def who(self, _request):
    return WhoResponse(
        host=auth.get_peer_host(),
        identity=auth.get_current_identity().to_bytes(),
        ip=auth.ip_to_string(auth.get_peer_ip()))

  @auth.endpoints_method(
      message_types.VoidMessage,
      message_types.VoidMessage,
      name='forbidden',
      http_method='GET')
  @auth.require(lambda: False)
  def forbidden(self, _request):
    pass

  @auth.endpoints_method(
      HostTokenRequest,
      HostTokenRespones,
      name='create_host_token',
      http_method='POST')
  @auth.public
  def create_host_token(self, request):
    return HostTokenRespones(host_token=auth.create_host_token(request.host))


app = endpoints.api_server([TestingServiceApi])
Beispiel #31
0
    @endpoints.method(request_message=GET_GAME_REQUEST,
                      response_message=StringMessage,
                      path='game/{urlsafe_game_key}/history',
                      name='get_game_history',
                      http_method='GET')
    def get_game_history(self, request):
        """Get a game's history (moves made so far)"""
        game = get_by_urlsafe(request.urlsafe_game_key, Game)

        if game:
            return StringMessage(message='History: ' + str(game.history))
        else:
            raise endpoints.NotFoundException('Game not found!')

    @staticmethod
    def _cache_average_attempts():
        """Populates memcache with the average moves remaining of Games"""
        games = Game.query(Game.game_over == False).fetch()
        if games:
            count = len(games)
            total_attempts_remaining = sum(
                [game.attempts_remaining for game in games])
            average = float(total_attempts_remaining) / count
            memcache.set(
                MEMCACHE_MOVES_REMAINING,
                'The average moves remaining is {:.2f}'.format(average))


api = endpoints.api_server([HangmanAPI])



@endpoints.api(name='ebaybidsendpoints', version='v1')
class EbayBidsApi(remote.Service):
    """EbayBidsApi API v1."""

    #@endpoints.method(message_types.VoidMessage, Bid,
    #  path = "noInput", http_method='GET', name = "noInput")
    #def noInput(self, request):
    #  return Bid(msg="No User Input Yet")

    @endpoints.method(REQUEST_CONTAINER, Bid,
      path = "calculateClosing", http_method='GET', name = "calculateClosing")
    def calculuate_Closing(self, request):
      #calculate delta from ols model
      o = float(request.opening)
      d = (-0.224271) + (0.066683*request.average) + (3.070601*request.std)
      c = o + d
      retval = Bid(msg = "success", 
        opening = o, 
        delta = d, 
        closing = c)

      return retval



APPLICATION = endpoints.api_server([EbayBidsApi])
        # both for data model & outbound Message
        if data["maxAttendees"] > 0:
            data["seatsAvailable"] = data["maxAttendees"]
            setattr(request, "seatsAvailable", data["maxAttendees"])

        # make Profile Key from user ID
        p_key = ndb.Key(Profile, user_id)
        # allocate new Conference ID with Profile key as parent
        c_id = Conference.allocate_ids(size=1, parent=p_key)[0]
        # make Conference key from ID
        c_key = ndb.Key(Conference, c_id, parent=p_key)
        data['key'] = c_key
        data['organizerUserId'] = request.organizerUserId = user_id

        # create Conference & return (modified) ConferenceForm
        Conference(**data).put()

        return request


    @endpoints.method(ConferenceForm, ConferenceForm, path='conference',
            http_method='POST', name='createConference')
    def createConference(self, request):
        """Create new conference."""
        return self._createConferenceObject(request)



# registers API
api = endpoints.api_server([ConferenceApi])
Beispiel #34
0
        appstats_routes.append(('/admin/stats/%s' % path[3:], handler))

# i18n configuration for jinja2
webapp2_i18n_config = {'translations_path': os.path.join(
    appengine_config.BUNDLE_ROOT, 'modules/i18n/resources/locale')}

rosebotics_routes = [('/', main_handler.HomePage),
                     ('/courses', main_handler.CoursesPage),
                     ('/competition', main_handler.CompetitionPage),
                     ('/platform', main_handler.PlatformPage),
                     ('/web', course_handlers.WebCoursePage),
                     ('/ios', course_handlers.IosCoursePage),
                     ('/android', course_handlers.AndroidCoursePage),
                     ('/me430', course_handlers.Me430CoursePage),
                     ('/editprofile', main_handler.EditProfileAction),
                     ('/resume', main_handler.ResumeRedirect),
                     ('/teams/', main_handler.TeamsPage),
                     ('/teams/export.csv', main_handler.ExportCsvAction),
                     ('/cron/teams/autosweeps', cron_handler.AutoSweepCronJob),]

# init application
app = webapp2.WSGIApplication(
    rosebotics_routes + global_routes + appstats_routes + app_routes,
    config={'webapp2_extras.i18n': webapp2_i18n_config},
    debug=not appengine_config.PRODUCTION_MODE)

# init api
api = endpoints.api_server([teams_api.TeamApi], restricted = False)


                new_speakerKey[session.speaker.websafeSpeakerKey] += 1
                if new_speakerKey[session.speaker.websafeSpeakerKey] > 1:
                    featuredSpeaker['name'] = session.speaker.name
                    featuredSpeaker['email'] = session.speaker.email
                    break

        if any(featuredSpeaker):
            # If there is a featured speaker we put it in the memcache
            speaker = 'Come and listen to the best speakers! %s, %s, %s %s' % (
                featuredSpeaker['name'], featuredSpeaker['email'],
                'is going to attend the:', conference.name + ' conference!')
            memcache.set(MEMCACHE_SPEAKERS_KEY, speaker)

        return featuredSpeaker

    @endpoints.method(message_types.VoidMessage,
                      StringMessage,
                      path='conference/getFeaturedSpeaker',
                      http_method='GET',
                      name='getFeaturedSpeaker')
    def getFeaturedSpeaker(self, request):
        """Get featured speakers."""
        speaker = memcache.get(MEMCACHE_SPEAKERS_KEY)
        if not speaker:
            speaker = 'There are no featured speakers'
        return StringMessage(data=speaker)


# registers API
api = endpoints.api_server([ConferenceApi])
Beispiel #36
0

# GET AVERAGE WIN RATES -------------------------------------

    @endpoints.method(response_message=StringMessage,
                      path='games/average_win_rates',
                      name='get_average_win_rates',
                      http_method='GET')
    def get_average_win_rates(self, request):
        """Get the cached average win rate"""
        return StringMessage(message=memcache.get(MEMCACHE_WIN_RATES) or '')


# CACHE AVERAGE WIN RATES ----------------------------

    @staticmethod
    def _cache_average_win_rates():
        """Populates memcache with the average win rates of Games"""
        # games_win = len(Game.query(Game.winner == "X").fetch())
        # games_over = len(Game.query(Game.game_over == True).fetch())
        games_win = Game.query(Game.winner == "X").count()        
        games_over = Game.query(Game.game_over == True).count()

        if games_over > 0:
            average = float(games_win)/games_over
            memcache.set(MEMCACHE_WIN_RATES,
                         'The average win rate is {:.2f}'.format(average))


api = endpoints.api_server([TicTacToeApi])
Beispiel #37
0

# [END data_process_api]


# [START data_results_api]
@api_collection.api_class(resource_name='results')
#@endpoints.api(name='results', version='v1')
class MelanomaResults(remote.Service):

    # [START echo_api_method]
    @endpoints.method(
        # This method takes a ResourceContainer defined above.
        MELANOMA_RESOURCE,

        # This method returns an Echo message.
        MelanomaResponse,
        path='diagnostic',
        http_method='POST',
        name='get_diagnostic')
    def get_diagnostic(self, request):
        output_message = ' '.join([request.message] * request.n)
        return MelanomaResponse(message=output_message)


# [END data_process_api]

# [START api_server]
api = endpoints.api_server([api_collection])
# [END api_server]
Beispiel #38
0
                                 required=True),  # noqa
    choices=messages.StringField(2, required=True))

WEB_CLIENT_ID = '471311115005-4bd8aqpnmrnro61ntdgstb2bsbvhma90.apps.googleusercontent.com'  # noqa
ANDROID_CLIENT_ID = ''
IOS_CLIENT_ID = ''
ANDROID_AUDIENCE = WEB_CLIENT_ID


@endpoints.api(
    name='wordsapi',
    version='v1',
    allowed_client_ids=[WEB_CLIENT_ID,
                        endpoints.API_EXPLORER_CLIENT_ID],  # noqa
    audiences=[ANDROID_AUDIENCE],
)
class WordsApi(remote.Service):
    @endpoints.method(WORDS_CRITERIA_RESOURCE,
                      Words,
                      path='words/{length}/{choices}',
                      http_method='POST',
                      name='words.get')
    def get_words(self, request):
        words = utils.get_words(request.length, request.choices.upper())
        return Words(words=[
            Word(word=w, frequency=str(utils.WORDS.get(w))) for w in words
        ])  # noqa


app = endpoints.api_server([WordsApi])
Beispiel #39
0
        """Return a Game's move history"""
        game = get_by_urlsafe(request.urlsafe_game_key, Game)
        if not game:
            raise endpoints.NotFoundException('Game not found')
        return StringMessage(message=str(game.historyMoves))

    @endpoints.method(response_message=ScoreForms,
                      path='scores',
                      name='get_scores',
                      http_method='GET')
    def get_scores(self, request):
        """Return all scores"""
        return ScoreForms(items=[score.to_form() for score in Score.query()])

    @endpoints.method(request_message=USER_REQUEST,
                      response_message=ScoreForms,
                      path='scores/user/{user_name}',
                      name='get_user_scores',
                      http_method='GET')
    def get_user_scores(self, request):
        """Returns all of an individual User's scores"""
        user = User.query(User.name == request.user_name).get()
        if not user:
            raise endpoints.NotFoundException(
                'A User with that name does not exist!')
        scores = Score.query(ndb.OR(Score.playerX == user.key,
                                    Score.playerO == user.key))
        return ScoreForms(items=[score.to_form() for score in scores])

api = endpoints.api_server([gameAPI])
Beispiel #40
0
 def app_module(self):
     """WSGI module that wraps the API class, used by AppengineTestCase."""
     return endpoints.api_server([self.api_service_cls], restricted=False)
Beispiel #41
0
def create_endpoints_app():
    return endpoints.api_server([config.ConfigApi])
Beispiel #42
0
        return tuple_list

    @endpoints.method(endpoints.ResourceContainer(
        spkr_wkey=messages.StringField(1), conf_wkey=messages.StringField(2)),
                      StringMessage,
                      http_method='GET',
                      name='testTask')
    def _testTask(self, request):
        """developer endpoint method to test featured speaker

        Debug purposes"""
        return StringMessage(data=self._cacheFeaturedSpeaker(
            request.spkr_wkey, request.conf_wkey))

    @endpoints.method(
        endpoints.ResourceContainer(sess_wkey=messages.StringField(1)),
        StringMessage,
        http_method='GET',
        name='testHelp')
    def _testHelp(self, request):
        """developer endpoint method to help massage data

        Debug purposes"""
        prof = self._getProfileFromUser()
        prof.sessionKeysInWishlist.remove(request.sess_wkey)
        prof.put()
        return StringMessage(data='done')

api = endpoints.api_server([ConferenceApi])  # register API
Beispiel #43
0
        if not request.from_datastore:
            raise endpoints.NotFoundException("Key not in datastore")
        else:
            request.key.delete()
        return DbEvent(quote="deleted")


#     @DbComment.method(name="dbcomment.insert", path="haystack/dbcomment/insert", http_method="POST")
#     def dbcomment_insert(self, request):
#         if request.from_datastore:
#             my_quote = request
#         else:
#             my_quote = DbComment(event_id=request.event_id, comment=request.comment)
#         my_quote.put()
#         return my_quote
#
#     @DbComment.query_method(query_fields=("order", "limit", "pageToken"), name="dbcomment.list", path="haystack/dbcomment/insert", http_method="GET")
#     def dbcomment_list(self, query):
#         return query
#
#     @DbComment.method(name="dbcomment.delete", path="haystack/dbcomment/delete/{entityKey}", http_method="DELETE",
#                        request_fields=("entityKey",))
#     def dbcomment_delete(self, request):
#         if not request.from_datastore:
#             raise endpoints.NotFoundException("Key not in datastore")
#         else:
#             request.key.delete()
#         return DbComment(quote="deleted")

app = endpoints.api_server([HaystackApi], restricted=False)
Beispiel #44
0
# Main handler for the requests. Routes the paths to the methods

import endpoints
from api.api_gup import CollectApi

api_application = endpoints.api_server([
    CollectApi,
], restricted=False)
Beispiel #45
0
        for timeseries in data['timeseries']:
            points = []
            fields = []
            for point in timeseries['points']:
                points.append(
                    Point(time=float(point['time']),
                          value=float(point['value'])))
            for field in timeseries['fields']:
                fields.append(Field(key=field['key'], value=field['value']))
            tsList.append(
                TimeSeries(points=points,
                           fields=fields,
                           metric=timeseries['metric']))
        futures = [timeseries_query(t) for t in tsList]
        ndb.Future.wait_all(futures)
        for future in futures:
            future.get_result()
        return message_types.VoidMessage()


handlers = [
    ('/tasks/clean_outdated_graphs', CronHandler),
    ('/timeseries_update', TimeSeriesHandler),
]

WEBAPP = add_appstats(webapp2.WSGIApplication(handlers, debug=True))

APPLICATION = add_appstats(
    ndb.toplevel(endpoints.api_server([ConsoleAppApi, UIApi,
                                       config.ConfigApi])))
Beispiel #46
0
import endpoints

import ImageAPIs
import StreamAPIs

APPLICATION = endpoints.api_server([StreamAPIs.StreamAPI, ImageAPIs.ImageAPI])
Beispiel #47
0
import endpoints
from services.sample_endpoints import ApiService

__author__ = 'faisal'

# Now create the server and see how its added in app.yaml
# Please refer to the official docs on how to generate client libraries at
# https://developers.google.com/appengine/docs/python/endpoints/gen_clients
# Check base.html for js tests
application = endpoints.api_server([ApiService], restricted=False)
Beispiel #48
0
                        scanned.
      scanned_repos:  the number of repositories which have at least been
                      partially scanned.
      repos_without_root:  the number of repositories which have not yet been
                           fully scanned.
      repos_with_root:  the number of repositories which have been fully
                        scanned.
      generated:  when the statistic was generated.
      p50-99: 50th, 75th, 90th, 95th, and 99th percentile seconds since
              repositories were last scanned.
      min, max:  minimum/maximum seconds since a repository was last scanned.
      most_lagging_repo:  the project:repo that has the most scan lag.
    """
        return controller.calculate_lag_stats(generated=request.generated)

    @models.RepoScanPipelineList.method(
        request_fields=('project', ),
        path='repo_scan_pipeline_list/{project}',
        http_method='GET',
        name='repo_scan_pipeline_list.get')
    def get_repo_scan_pipeline_list(self, request):  # pragma: no cover
        return models.RepoScanPipelineList(
            project=request.project,
            repos=list(
                models.RepoScanPipeline.query(
                    models.RepoScanPipeline.project == request.project).order(
                        models.RepoScanPipeline.started)))


APPLICATION = endpoints.api_server([CrRevApi])
Beispiel #49
0
class Hello(messages.Message):
    """String that stores a message."""
    greeting = messages.StringField(1)


@endpoints.api(name='helloworldendpoints', version='v1')
class HelloWorldApi(remote.Service):
    """Helloworld API v1."""
    @endpoints.method(message_types.VoidMessage,
                      Hello,
                      path="sayHello",
                      http_method='GET',
                      name="sayHello")
    def say_hello(self, request):
        logging.info("sayHello endpoint invoked.")
        return Hello(greeting="Hello World")

    @endpoints.method(REQUEST_CONTAINER,
                      Hello,
                      path="sayHelloByName",
                      http_method='GET',
                      name="sayHelloByName")
    def say_hello_by_name(self, request):
        logging.info("sayHelloByName endpoint invoked.")
        greet = "Hello {}".format(request.name)
        return Hello(greeting=greet)


app = endpoints.api_server([HelloWorldApi])
Beispiel #50
0
        """Return user's move history for the game.
        Args:
            request: The GET_GAME_REQUEST object, which includes
             the game's urlsafe_game_key.
        Returns:
            GameHistory: The list of moves with the results for each move.
        Raises:
            endpoints.NotFoundException: If no game is found for the urlsafe_game_key.
        """
        game = get_by_urlsafe(request.urlsafe_game_key, Game)
        if game:
            return GameHistory(move=str(game.move_history))
        else:
            raise endpoints.NotFoundException('Game not Found!')

    @staticmethod
    def _cache_average_attempts():
        """Populates memcache with the average moves remaining of Games."""
        games = Game.query(Game.game_over == False)
        if games:
            count = games.count()
            total_attempts_remaining = sum(
                [game.attempts_remaining for game in games])
            average = total_attempts_remaining / float(count)
            memcache.set(
                MEMCACHE_MOVES_REMAINING,
                'The average moves remaining is {:.2f}'.format(average))


api = endpoints.api_server([HangmanApi])
Beispiel #51
0
	# permette di dare una preferenza ad una risposta.
	@endpoints.method(GDGPEQuestionAnswerRatingRequest,GDGPEQuestionAnswerRatingResponse,name="gdgPE.questionAnswer.rate",http_method="POST")
	def rateQuestionAnswer(self,request):
		L.i(request)
		return
	#
	# User
	#
	@endpoints.method(GDGPESubscribeUserRequest, GDGPESubscribeUserResponse, name="gdgPE.user.subscribe",http_method="POST")
	def subscribeUser(self,request):
		L.i(request)
		return ""
	
	@endpoints.method(GDGPEUnsubscribeUserRequest, GDGPEUnsubscribeUserResponse, name="gdgPE.user.unsubscribe",http_method="POST")
	def unsubscribeUser(self,request):
		L.i(request)
		return ""
	
	@endpoints.method(GDGPEUserInfoRequest, GDGPEUserInfoResponse, name="gdgPE.user.info", http_method="POST")
	def userInfo(self,request):
		L.i(request)
		return
	
# see application.yaml
APPLICATION=endpoints.api_server([GDGPEEndpoint], restricted=False)





Beispiel #52
0

# [START authed_greeting_api]
@endpoints.api(
    name='authed_greeting',
    version='v1',
    # Only allowed configured Client IDs to access this API.
    allowed_client_ids=ALLOWED_CLIENT_IDS,
    # Only allow auth tokens with the given audience to access this API.
    audiences=[ANDROID_AUDIENCE],
    # Require auth tokens to have the following scopes to access this API.
    scopes=[endpoints.EMAIL_SCOPE])
class AuthedGreetingApi(remote.Service):

    @endpoints.method(
        message_types.VoidMessage,
        Greeting,
        path='greet',
        http_method='POST',
        name='greet')
    def greet(self, request):
        user = endpoints.get_current_user()
        user_name = user.email() if user else 'Anonymous'
        return Greeting(message='Hello, {}'.format(user_name))
# [END authed_greeting_api]


# [START api_server]
api = endpoints.api_server([GreetingApi, AuthedGreetingApi])
# [END api_server]
Beispiel #53
0
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.

xamoom-wordpress is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with open xamoom.  If not, see <http://www.gnu.org/licenses/>.
"""

""" This module initializes the Google Cloud Endpoints API server with all API classes.
This module and the API server instance (APPLICATION) is referenced in app.yaml.
This file is part of open-xamoom.  """

import endpoints
from xamoom_enduser_api import XamoomEndUserApi
from xamoom_integration_api import XamoomIntegrationApi

__author__ = "xamoom GmbH, Bruno Hautzenberger"

__version__ = "19.2.1.6"
__maintainer__ = "Bruno Hautzenberger"
__email__ = "*****@*****.**"
__status__ = "Production"


# The API server instance
APPLICATION = endpoints.api_server([XamoomIntegrationApi, XamoomEndUserApi])
Beispiel #54
0
        if not user:
            raise endpoints.NotFoundException(
                'A User with that name does not exist!')
        scores = Score.query(Score.user == user.key)
        return ScoreForms(items=[score.to_form() for score in scores])

    @endpoints.method(response_message=StringMessage,
                      path='games/average_attempts',
                      name='get_average_attempts_remaining',
                      http_method='GET')
    def get_average_attempts(self, request):
        """Get the cached average moves remaining"""
        return StringMessage(
            message=memcache.get(MEMCACHE_MOVES_REMAINING) or '')

    @staticmethod
    def _cache_average_attempts():
        """Populates memcache with the average moves remaining of Games"""
        games = Game.query(Game.game_over == False).fetch()
        if games:
            count = len(games)
            total_attempts_remaining = sum(
                [game.attempts_remaining for game in games])
            average = float(total_attempts_remaining) / count
            memcache.set(
                MEMCACHE_MOVES_REMAINING,
                'The average moves remaining is {:.2f}'.format(average))


api = endpoints.api_server([GuessANumberApi])
Beispiel #55
0
    # create private method which relates to main.py
    @staticmethod
    def _cache_incomplete_games():
        """Populates memcache with the incomplete Games and lets you know whos turn it is"""
        games = Game.query(ndb.OR(Game.winner1 == False,
                                  Game.winner2 == False)).fetch()
        # returns a list of games
        if games:
            for game in games:
                if len(game.moves) < 9:
                    if len(game.player1_position) > len(game.player2_position):
                        announcement = 'It is {}s turn.'.format(game.player1.get().name)
                        # game.player1 returns (Player, somekey)
                        # we need the name form the instance in Player
                        memcache.set(MEMCACHE_INCOMPLETE_GAMES, announcement)
                        # you need for set -> set(some_key,some_string)
                    else:
                        announcement = 'It is {}s turn.'.format(game.player2.get().name)
                        memcache.set(MEMCACHE_INCOMPLETE_GAMES, announcement)
                else:
                    announcement = "Game is tied"
                    memcache.delete(MEMCACHE_INCOMPLETE_GAMES)
        else:
            announcement = "no games"
            memcache.delete(MEMCACHE_INCOMPLETE_GAMES)
        return announcement


# name from class in endpoints.api will be reused in here
api = endpoints.api_server([tictactoeAPI])
Beispiel #56
0
import endpoints

from rpc import wordAPI
package = 'omerrdict'

APPLICATION = endpoints.api_server([wordAPI.WordAPIApi])

@endpoints.api(name='shouter', version='v1', owner_name='dcifuen',
               allowed_client_ids=[WEB_CLIENT_ID,
                                   endpoints.API_EXPLORER_CLIENT_ID], )
class ShouterApi(remote.Service):
    """Shouter API v1."""

    @endpoints.method(GreetingMessage, GreetingMessage,
                      path='shouter', http_method='POST',
                      name='greeting.update')
    def greeting_update(self, request):
        greeting = Greeting.get_by_id(1)
        if not greeting:
            greeting = Greeting(id=1)
        greeting.message = request.message
        greeting.put()
        return GreetingMessage(message=request.message)

    @endpoints.method(VoidMessage, GreetingMessage,
                      path='shouter', http_method='GET',
                      name='greeting.get')
    def greeting_get(self, request):
        greeting = Greeting.get_by_id(1)
        if not greeting:
            raise endpoints.NotFoundException('Greeting not found')
        return GreetingMessage(message=greeting.message)


APPLICATION = endpoints.api_server([ShouterApi])
                      http_method='GET',
                      name='greetings.getGreeting')
    def greeting(self, request):
        try:
            return STORED_GREETINGS.items[request.id]
        except:
            return endpoints.NotFoundException('Greeting %s not found.' %
                                               request.id)

    @endpoints.method(GreetingForm,
                      GreetingForm,
                      path='hellogreeting',
                      http_method='POST',
                      name='greeting.addGreeting')
    def addGreeting(self, request):
        """Add greeting with user's profile as parent"""
        profile = self._getProfileFromUser()
        p_key = ndb.Key(Profile, profile.email)
        g = Greeting(message=request.message, parent=p_key)
        g.put()
        return request

    @endpoints.method(message_types.VoidMessage, ProfileForm)
    def returnPofile(self, unused_request):
        """Return a user's profile"""
        profile = self._getProfileFromUser()
        return self._copyProfileToForm(profile)


APPLICATION = endpoints.api_server([HelloWorldApi])
  # case of a 401, the method will not be executed. Conversely, if method
  # execution occurs, user_required=True will guarantee that the current user is
  # valid.
  @MyModel.method(user_required=True,
                  path='mymodel', http_method='POST', name='mymodel.insert')
  def MyModelInsert(self, my_model):
    # Since user_required is True, we know endpoints.get_current_user will
    # return a valid user.
    my_model.owner = endpoints.get_current_user()
    # Also note, since we don't override the default ProtoRPC message schema,
    # API users can send an owner object in the request, but we overwrite the
    # model property with the current user before the entity is inserted into
    # the datastore and this put operation will only occur if a valid token
    # identifying the user was sent in the Authorization header.
    my_model.put()
    return my_model

  # As above with MyModelInsert, we add user_required=True to the arguments
  # passed to the MyModel.query_method decorator in basic/main.py. Therefore,
  # only queries can be made by a valid user.
  @MyModel.query_method(user_required=True,
                        path='mymodels', name='mymodel.list')
  def MyModelList(self, query):
    # We only allow users to query the MyModel entities that they have created,
    # so query using owner equal to the current user. Since user_required is
    # set, we know get_current_user will return a valid user.
    return query.filter(MyModel.owner == endpoints.get_current_user())


application = endpoints.api_server([MyApi], restricted=False)
Beispiel #60
0
        # This method returns an Echo message.
        Echo,
        path='echo',
        http_method='POST',
        name='echo')
    def echo(self, request):
        return Echo(content=request.content)

    @endpoints.method(
        # This method takes an empty request body.
        message_types.VoidMessage,
        # This method returns an Echo message.
        Echo,
        path='echo/getUserEmail',
        http_method='GET',
        # Require auth tokens to have the following scopes to access this API.
        scopes=[endpoints.EMAIL_SCOPE])
    def get_user_email(self, request):
        user = endpoints.get_current_user()
        # If there's no user defined, the request was unauthenticated, so we
        # raise 401 Unauthorized.
        if not user:
            raise endpoints.UnauthorizedException
        return Echo(content=user.email())
# [END echo_api]


# [START api_server]
api = endpoints.api_server([EchoApi])
# [END api_server]