class TestApi(remote.Service): """A handler for Test API.""" @base.ApiMethod(endpoints.ResourceContainer(message_types.VoidMessage), mtt_messages.TestList, path='/tests', http_method='GET', name='list') def List(self, request): """Lists test suites.""" tests = list(ndb_models.Test.query().order(ndb_models.Test.name)) test_msgs = mtt_messages.ConvertList(tests, mtt_messages.Test) return mtt_messages.TestList(tests=test_msgs) @base.ApiMethod(endpoints.ResourceContainer(mtt_messages.Test), mtt_messages.Test, path='/tests', http_method='POST', name='create') def Create(self, request): """Creates a test suite. Body: Test suite data """ test = mtt_messages.Convert(request, ndb_models.Test, from_cls=mtt_messages.Test) test.put() return mtt_messages.Convert(test, mtt_messages.Test) @base.ApiMethod(endpoints.ResourceContainer(message_types.VoidMessage, test_id=messages.StringField( 1, required=True)), mtt_messages.Test, path='{test_id}', http_method='GET', name='get') def Get(self, request): """Fetches a test suite. Parameters: test_id: Test ID, or zero for an empty test suite """ if request.test_id == '0': # For ID 0, return an empty test object to use as a template in UI. test = ndb_models.Test(name='') else: test = mtt_messages.ConvertToKey(ndb_models.Test, request.test_id).get() if not test: raise endpoints.NotFoundException('no test found for ID %s' % request.test_id) return mtt_messages.Convert(test, mtt_messages.Test) @base.ApiMethod(endpoints.ResourceContainer(mtt_messages.Test, test_id=messages.StringField( 1, required=True)), mtt_messages.Test, path='{test_id}', http_method='PUT', name='update') def Update(self, request): """Updates a test suite. Body: Test suite data Parameters: test_id: Test ID """ test = mtt_messages.ConvertToKey(ndb_models.Test, request.test_id).get() if not test: raise endpoints.NotFoundException('no test found for ID %s' % request.test_id) request.id = request.test_id test = mtt_messages.Convert(request, ndb_models.Test, mtt_messages.Test) test.put() return mtt_messages.Convert(test, mtt_messages.Test) @base.ApiMethod(endpoints.ResourceContainer(message_types.VoidMessage, test_id=messages.StringField( 1, required=True)), message_types.VoidMessage, path='{test_id}', http_method='DELETE', name='delete') def Delete(self, request): """Deletes a test suite. Parameters: test_id: Test ID """ test_key = mtt_messages.ConvertToKey(ndb_models.Test, request.test_id) test_key.delete() return message_types.VoidMessage()
"""Hello World API implemented using Google Cloud Endpoints. Contains declarations of endpoint, endpoint methods, as well as the ProtoRPC message class and container required for endpoint method definition. """ import endpoints from protorpc import messages from protorpc import message_types from protorpc import remote # If the request contains path or querystring arguments, # you cannot use a simple Message class. # Instead, you must use a ResourceContainer class REQUEST_CONTAINER = endpoints.ResourceContainer( message_types.VoidMessage, name=messages.StringField(1), ) class greetByPeriodRequest(messages.Message): name = messages.StringField(1) period = messages.StringField(2) package = 'Hello' class Hello(messages.Message): """String that stores a message.""" greeting = messages.StringField(1)
'GT': '>', 'GTEQ': '>=', 'LT': '<', 'LTEQ': '<=', 'NE': '!=' } FIELDS = { 'CITY': 'city', 'TOPIC': 'topics', 'MONTH': 'month', 'MAX_ATTENDEES': 'maxAttendees', } CONF_GET_REQUEST = endpoints.ResourceContainer( message_types.VoidMessage, websafeConferenceKey=messages.StringField(1), ) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @endpoints.api(name='conference', version='v1', allowed_client_ids=[WEB_CLIENT_ID, API_EXPLORER_CLIENT_ID], scopes=[EMAIL_SCOPE]) class ConferenceApi(remote.Service): """Conference API v0.1""" # - - - Conference objects - - - - - - - - - - - - - - - - - def _copyConferenceToForm(self, conf, displayName):
'GT': '>', 'GTEQ': '>=', 'LT': '<', 'LTEQ': '<=', 'NE': '!=' } FIELDS = { 'CITY': 'city', 'TOPIC': 'topics', 'MONTH': 'month', 'MAX_ATTENDEES': 'maxAttendees', } CONF_GET_REQUEST = endpoints.ResourceContainer( message_types.VoidMessage, websafeConferenceKey=messages.StringField(1), ) CONF_POST_REQUEST = endpoints.ResourceContainer( ConferenceForm, websafeConferenceKey=messages.StringField(1), ) SESS_GET_REQUEST = endpoints.ResourceContainer( message_types.VoidMessage, websafeConferenceKey=messages.StringField(1), ) SESS_TYPE_GET_REQUEST = endpoints.ResourceContainer( typeOfSession=messages.EnumField(TypeOfSession, 1), websafeConferenceKey=messages.StringField(2),
GameHistory, ) from models.score import ( Score, ScoreForms, ) from models.user import ( User, UserForms, ) from utils import get_by_urlsafe API_EXPLORER_CLIENT_ID = endpoints.API_EXPLORER_CLIENT_ID GET_GAME_REQUEST = endpoints.ResourceContainer( urlsafe_game_key=messages.StringField(1), ) GET_USER_REQUEST = endpoints.ResourceContainer( user_name=messages.StringField(1), ) GET_HIGH_SCORES_REQUEST = endpoints.ResourceContainer( number_of_results=messages.IntegerField(1), ) MAKE_MOVE_REQUEST = endpoints.ResourceContainer( urlsafe_game_key=messages.StringField(1), move=messages.StringField(2), ) NEW_GAME_REQUEST = endpoints.ResourceContainer(NewGameForm) USER_REQUEST = endpoints.ResourceContainer(user_name=messages.StringField(1),
u'uetopia_connected': self.uetopia_connected, u'admin': self.admin, u'metaGameActive': self.metaGameActive, u'roundActionUsed': self.roundActionUsed, u'currentFactionTag': self.currentFactionTag, u'currentFactionLead': self.currentFactionLead, u'currentFactionTeamLead': self.currentFactionTeamLead, u'currentTeamCaptain': self.currentTeamCaptain, u'holdingZoneKeyId': self.holdingZoneKeyId, u'holdingZone': self.holdingZone, u'holdingZoneTitle': self.holdingZoneTitle }) ### PROTORPC MODELS FOR ENDPOINTS ### These are used to specify incoming and outgoing variables from the endpoints API class UserResponse(messages.Message): """ a user's data """ key_id = messages.IntegerField(1, variant=messages.Variant.INT32) title = messages.StringField(2) uetopia_connected = messages.BooleanField(6) class UserRequest(messages.Message): """ a users updates """ key_id = messages.IntegerField(1, variant=messages.Variant.INT32) security_code = messages.StringField(2) USER_RESOURCE = endpoints.ResourceContainer(UserRequest)
# -*- coding: utf-8 -*-` """api.py - Create and configure the Game API exposing the resources. This can also contain game logic. For more complex games it would be wise to move game logic to another file. Ideally the API will be simple, concerned primarily with communication to/from the API's users.""" import logging import endpoints from protorpc import remote, messages from models import User, Game, Score, GameForm, GameForms, NewGameForm, MakeMoveForm, ScoreForm, ScoreForms, StringMessage, UserForm, UserForms from utils import get_by_urlsafe, lookForWin, boolFullCurrentBoard from google.appengine.api import memcache, mail from google.appengine.ext import ndb from google.appengine.api import taskqueue NEW_GAME_REQUEST = endpoints.ResourceContainer(NewGameForm) GET_GAME_REQUEST = endpoints.ResourceContainer( urlsafe_game_key=messages.StringField(1),) MAKE_MOVE_REQUEST = endpoints.ResourceContainer( MakeMoveForm, urlsafe_game_key=messages.StringField(1),) # ResourceContainer is used for Querystring parameters USER_REQUEST = endpoints.ResourceContainer(user_name=messages.StringField(1), email=messages.StringField(2)) @endpoints.api(name='tic_tac_toe', version='v1') class gameAPI(remote.Service): """Game API""" @endpoints.method(request_message=USER_REQUEST, response_message=StringMessage,
from forms.stringmessages import StringMessages from forms.boardform import BoardForm from forms.newgameform import NewGameForm from forms.gameform import GameForm from forms.gameforms import GameForms from forms.makemoveform import MakeMoveForm from forms.scoreforms import ScoreForms from forms.placeshipform import PlaceShipForm from forms.fleetstatusform import FleetStatusForm from forms.gamehistoryform import GameHistoryForm from utils import get_by_urlsafe, ai_fleet_builder from settings import WEB_CLIENT_ID API_EXPLORER_CLIENT_ID = endpoints.API_EXPLORER_CLIENT_ID NEW_GAME_REQUEST = endpoints.ResourceContainer(NewGameForm) PLACE_SHIP_REQUEST = endpoints.ResourceContainer( PlaceShipForm, urlsafe_game_key=messages.StringField(1)) GET_GAME_REQUEST = endpoints.ResourceContainer( urlsafe_game_key=messages.StringField(1), ) BOARD_REQUEST = endpoints.ResourceContainer( urlsafe_game_key=messages.StringField(1), board=messages.StringField(2)) FLEET_REQUEST = endpoints.ResourceContainer( urlsafe_game_key=messages.StringField(1), fleet=messages.StringField(2)) MAKE_MOVE_REQUEST = endpoints.ResourceContainer( MakeMoveForm, urlsafe_game_key=messages.StringField(1), ) USER_REQUEST = endpoints.ResourceContainer(user_name=messages.StringField(1), user_pw=messages.StringField(2), email=messages.StringField(3))
'GT': '>', 'GTEQ': '>=', 'LT': '<', 'LTEQ': '<=', 'NE': '!=' } FIELDS = { 'CITY': 'city', 'TOPIC': 'topics', 'MONTH': 'month', 'MAX_ATTENDEES': 'maxAttendees', } CONF_GET_REQUEST = endpoints.ResourceContainer( message_types.VoidMessage, websafeConferenceKey=messages.StringField(1), ) CONF_POST_REQUEST = endpoints.ResourceContainer( ConferenceForm, websafeConferenceKey=messages.StringField(1), ) SESS_GET_REQUEST = endpoints.ResourceContainer( message_types.VoidMessage, websafeConferenceKey=messages.StringField(1), sessionType=messages.StringField(2), speaker=messages.StringField(3), ) SESS_POST_REQUEST = endpoints.ResourceContainer(
OPERATORS = { 'EQ': '=', 'GT': '>', 'GTEQ': '>=', 'LT': '<', 'LTEQ': '<=', 'NE': '!=' } FIELDS = { 'AUTHOR': 'author', 'TAGS': 'tags', } AUTHOR_UPDATE_REQUEST = endpoints.ResourceContainer( message_types.VoidMessage, websafeAuthorKey=messages.StringField(1), ) ARTICLE_BY_KEY_GET_REQUEST = endpoints.ResourceContainer( message_types.VoidMessage, websafeArticleKey=messages.StringField(1), ) ARTICLE_GET_REQUEST = endpoints.ResourceContainer( message_types.VoidMessage, authorID=messages.StringField(1), articleID=messages.StringField(2), ) ARTICLE_UPDATE_REQUEST = endpoints.ResourceContainer( ArticleUpdateForm,
class ServiceB(remote.Service): """Part B of a split service to test with.""" @endpoints.method(endpoints.ResourceContainer(), Message) def post_method(self, _): """An HTTP POST method.""" return Message()
Define all ResourceContainer used in conference.py """ import endpoints from protorpc import messages from protorpc import message_types from models import ConferenceForm, ConferenceQueryForm, ConferenceQueryMiniForm from models import SessionForm, SessionQueryForm __author__ = '[email protected] (Wiseley Wu)' CONF_GET_REQUEST = endpoints.ResourceContainer( message_types.VoidMessage, websafeConferenceKey=messages.StringField(1), ) CONF_GET_SIMILAR = endpoints.ResourceContainer( ConferenceQueryMiniForm, websafeConferenceKey=messages.StringField(1), ) CONF_POST_REQUEST = endpoints.ResourceContainer( ConferenceForm, websafeConferenceKey=messages.StringField(1), ) CREATE_SESSION = endpoints.ResourceContainer( SessionForm, websafeConferenceKey=messages.StringField(1),
class KReaderApi(remote.Service): @endpoints.method(User, User, path='/users', http_method='POST', name='add_user') def add_user(sell, request): return storage.add_user(request.name) @endpoints.method(Butter, Butter, path='/butter', http_method='POST', name='post_butter') def post_butter(self, request): return storage.add_butter(request) @endpoints.method(TagCollection, ButterCollection, path='/butters', http_method='GET', name='get_butters_by_tags') def get_butters_by_tags(self, request): keywords = [tag.name for tag in request.items] print('xoxo', keywords) butters = [ Butter(title=item['title']) for item in g_search.search(keywords) ] return ButterCollection(items=butters) FOLLOW_METHOD_RESOURCE = endpoints.ResourceContainer( Tag, user_name=messages.StringField(2, variant=messages.Variant.STRING, required=True)) @endpoints.method(FOLLOW_METHOD_RESOURCE, Tag, path='/{user_name}/tag/follow', http_method='POST', name='follow_tag') def follow_tag(self, request): storage.follow_tag(request.user_name, request.name) return storage.get_tag_by_name(request.name) GET_BUTTERS_METHOD_RESOURCE = endpoints.ResourceContainer( message_types.VoidMessage, user_name=messages.StringField(2, variant=messages.Variant.STRING, required=True)) @endpoints.method(GET_BUTTERS_METHOD_RESOURCE, ButterCollection, path='/{user_name}/butters', http_method='GET', name='get_butters_by_user_name') def get_butters_by_user_name(self, request): return ButterCollection( items=storage.get_butters_by_user_name(request.user_name)) LIST_FOLLOW_TAG_METHOD_RESOURCE = endpoints.ResourceContainer( message_types.VoidMessage, user_name=messages.StringField(2, variant=messages.Variant.STRING, required=True)) @endpoints.method(LIST_FOLLOW_TAG_METHOD_RESOURCE, TagCollection, path='/{user_name}/tags', http_method='GET', name='list_following_tags') def list_following_tags(self, request): tags = storage.get_following_tags_by_user_name(request.user_name) return TagCollection(items=tags)
key_id = messages.IntegerField(1, variant=messages.Variant.INT32) title = messages.StringField(2) description = messages.StringField(3) mapKeyId = messages.IntegerField(19, variant=messages.Variant.INT32) seasonKeyId = messages.IntegerField(20, variant=messages.Variant.INT32) regionKeyId = messages.IntegerField(22, variant=messages.Variant.INT32) horizontalIndex = messages.IntegerField(6, variant=messages.Variant.INT32) verticalIndex = messages.IntegerField(7, variant=messages.Variant.INT32) energy = messages.IntegerField(8, variant=messages.Variant.INT32) materials = messages.IntegerField(9, variant=messages.Variant.INT32) control = messages.IntegerField(10, variant=messages.Variant.INT32) validZone = messages.BooleanField(11) engine_travel_url = messages.StringField(12) ZONE_RESOURCE = endpoints.ResourceContainer(ZoneRequest) class ZoneCollection(messages.Message): """ multiple zones """ zones = messages.MessageField(ZoneResponse, 1, repeated=True) response_message = messages.StringField(40) response_successful = messages.BooleanField(50) class ZoneCollectionRequest(messages.Message): """ a zone collection request's data """ cursor = messages.StringField(1) sort_order = messages.StringField(2) direction = messages.StringField(3) mapKeyId = messages.IntegerField(5, variant=messages.Variant.INT32)
# [END imports] # [START messages] class EchoRequest(messages.Message): message = messages.StringField(1) class EchoResponse(messages.Message): """A proto Message that contains a simple string field.""" message = messages.StringField(1) ECHO_RESOURCE = endpoints.ResourceContainer(EchoRequest, n=messages.IntegerField(2, default=1)) # [END messages] # [START echo_api_class] @endpoints.api(name='echo', version='v1') class EchoApi(remote.Service): # [START echo_api_method] @endpoints.method( # This method takes a ResourceContainer defined above. ECHO_RESOURCE, # This method returns an Echo message. EchoResponse, path='echo',
'CITY': 'city', 'TOPIC': 'topics', 'MONTH': 'month', 'MAX_ATTENDEES': 'maxAttendees', } FIELDS_SESSION = { 'DURATION': 'duration', 'DATE': 'date', 'START_TIME': 'start_time', 'TYPE_OF_SESSION': 'type_of_session', } # Request message to get conference by conference key CONF_GET_REQUEST = endpoints.ResourceContainer( message_types.VoidMessage, websafeConferenceKey=messages.StringField(1), ) # Request message to post a conference by key and ConferenceForm CONF_POST_REQUEST = endpoints.ResourceContainer( ConferenceForm, websafeConferenceKey=messages.StringField(1), ) # Request message to get all session in a conference, by conference key SESSION_GET_REQUEST = endpoints.ResourceContainer( message_types.VoidMessage, websafeConferenceKey=messages.StringField(1), ) # Request message to get all sessions of a particular type
class NotesApi(remote.Service): NoteRequestContainer = endpoints.ResourceContainer( resources.NoteRepr, key=messages.StringField(1)) @endpoints.method(message_types.VoidMessage, resources.NoteCollection, path='notes', http_method='GET', name='notes.notesList') def note_list(self, request): items = [] for note in models.Note.query().fetch(): checklist_items = [] for i in note.checklist_items: checklist_items.append( resources.CheckListItemRepr(title=i.title, checked=i.checked)) files = [f.urlsafe() for f in note.files] r = resources.NoteRepr(key=note.key.urlsafe(), title=note.title, content=note.content, date_created=note.date_created, checklist_items=checklist_items, files=files) items.append(r) return resources.NoteCollection(items=items) @endpoints.method(resources.NoteRepr, resources.NoteRepr, path='notes', http_method='POST', name='notes.notesCreate') def note_create(self, new_resource): user = endpoints.get_current_user() if user is None: raise endpoints.UnauthorizedException() note = models.Note(parent=ndb.Key("User", user.nickname()), title=new_resource.title, content=new_resource.content) note.put() new_resource.key = note.key.urlsafe() new_resource.date_created = note.date_created return new_resource @endpoints.method(resources.NoteCollection, message_types.VoidMessage, path='notes', http_method='PUT', name='notes.notesBatchUpdate') def note_batch_update(self, request): for note_repr in request.items: note = ndb.Key(urlsafe=note_repr.key).get() note.title = note_repr.title note.content = note_repr.content checklist_items = [] for item in note_repr.checklist_items: checklist_items.append( models.CheckListItem(title=item.title, checked=item.checked)) note.checklist_items = checklist_items files = [] for file_id in note_repr.files: try: files.append(ndb.Key(urlsafe=file_id).get()) except TypeError: continue note.files = files note.put() return message_types.VoidMessage() @endpoints.method(message_types.VoidMessage, message_types.VoidMessage, path='notes', http_method='DELETE', name='notes.notesBatchDelete') def note_list_delete(self, request): # https://code.google.com/p/googleappengine/issues/detail?id=11371 raise errors.MethodNotAllowed() @endpoints.method(NoteRequestContainer, resources.NoteRepr, path='notes/{key}', http_method='GET', name='notes.notesDetail') def note_get(self, request): note = ndb.Key(urlsafe=request.key).get() checklist_items = [] for i in note.checklist_items: checklist_items.append( resources.CheckListItemRepr(title=i.title, checked=i.checked)) files = [f.urlsafe() for f in note.files] return resources.NoteRepr(key=request.key, title=note.title, content=note.content, date_created=note.date_created, checklist_items=checklist_items, files=files) @endpoints.method(NoteRequestContainer, message_types.VoidMessage, path='notes/{key}', http_method='POST', name='notes.notesDetailPost') def note_get_post(self, request): raise errors.MethodNotAllowed() @endpoints.method(NoteRequestContainer, resources.NoteRepr, path='notes/{key}', http_method='PUT', name='notes.notesUpdate') def note_update(self, request): note = ndb.Key(urlsafe=request.key).get() note.title = request.title note.content = request.content checklist_items = [] for item in request.checklist_items: 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()
class PocketJukeAPI(remote.Service): """Pocket Juke API v1.""" @endpoints.method(add_response,Party_info, path='authed_partyInfo',http_method='GET', name='pocketjuke.getpartyinfoAuthed') def get_partyInfo(self,request): party_query = Party_.query(Party_.name == request.response) active_user = endpoints.get_current_user(); playlist_queue = [] if party_query.get(): #request_party = party_query.get() #user = User.query(User.user_id == active_user.user_id()) #if party_query.get(keys_only=True) == user.party_key: activity_query = Activity.query(Activity.party_key == party_query.get(keys_only=True)).order(Activity.song,Activity.time_stamp) if activity_query.get(): #we need to get all of the activities so we can build the queue #we dont need to sort the response, because the response is sorted already #set up our constant values #One of them is the maximum time between votes to be considered consecutive max_time_apart = 5 #this is in seconds #this one is for the time frame before the end of the current song max_before_start = 2000 #this is in miliseconds #this is the threshold minimum number of consecutive songs min_consect_songs = 3 #variable to keep track of the total number of consecutive songs consect_songs = 0 #for the consecutive songs the buff is .1 % consect_buff = 1.001 #buff for a standard vote vote_buff = 1.0005 #for the before the end of the current song buff its .5% before_buff = 1.005 queue = [] pre_entry = None def close_time(date1,date2): if(date1.year == date2.year): if(date1.month == date2.month): if(date1.day == date2.day): if(date1.hour == date2.hour): if(date1.minute == date2.minute): if(date1.second - date2.second < 5): return True return False for entry in activity_query: if not any(d['track_id'] == entry.song.get().track_id for d in queue): consect_songs = 0 new_activity = Activity_class(track_id = entry.song.get().track_id) song_pos = { 'weight' : 1, 'track_id': new_activity.track_id, } queue.append(song_pos) pre_entry = entry else: pos = map(itemgetter('track_id'),queue).index(entry.song.get().track_id) if consect_songs > min_consect_songs: weight = queue[pos]['weight'] queue[pos]["weight"] = weight * consect_buff else: weight = queue[pos]['weight'] queue[pos]["weight"] = weight * vote_buff if close_time(pre_entry.time_stamp,entry.time_stamp): consect_songs += 1 else: consect_songs = 0 #will add this back later #if entry.date.seconds() - 500000 < max_before_start: # queue[pos]['weight'] *= before_buff pre_entry = entry sorted_queue = sorted(queue, key=operator.itemgetter('weight'),reverse=True) #add the marked song that is in the active position song = Song.query(ndb.AND(Song.party_key == party_query.get(keys_only=True),Song.played == True)) if song.get(): active_song = song.get() playlist_queue.append(Activity_class(track_id = active_song.track_id)); else: active_song = Activity_class(track_id = '0') for activity in sorted_queue: if not activity['track_id'] == active_song.track_id: playlist_queue.append(Activity_class(track_id = activity['track_id'])) party = party_query.get() return Party_info(Activity_list = playlist_queue,attending = party.attending) else: party = party_query.get() playlist_queue.append(Activity_class(track_id='1')) return Party_info(Activity_list = playlist_queue,attending = party.attending) else: playlist_queue.append(Activity_class(track_id='2')) return Party_info(Activity_list = playlist_queue) @endpoints.method(Party_class,add_response, path='authed_addParty',http_method='PUT', name='pocketjuke.addPartyAuthed') def add_Party(self,request): party_query = Party_.query(Party_.name == request.name) if not party_query.get(): current_user = endpoints.get_current_user() user_query = User.query(User.user_id == current_user.user_id()) if user_query: user = user_query.get() new_party = Party_(name = request.name,party_creator = user_query.get(keys_only=True),code = request.code,attending =+1) user.party_key = new_party.put() user.put() return add_response(response='added party') else: return add_response(response="unable to add party") else: return add_response(response="party already exsists") @endpoints.method(message_types.VoidMessage,add_response, path='authed_addUser',http_method='POST', name='pocketjuke.addUserAuthed') def add_User(self,request): active_user = endpoints.get_current_user() user_query = User.query(User.user_id == active_user.user_id()) if user_query.get(): return add_response(response = 'User already in the database') else: new_user = User(user_id = active_user.user_id(),party_key = None) new_user.put() return add_response(response="user added to the database") QUANTITY = endpoints.ResourceContainer( Party_class,offset=messages.IntegerField(4, variant=messages.Variant.INT32)) @endpoints.method(QUANTITY,Party_list, path='authed_getParty',http_method='GET', name='pocketjuke.getPartysAuthed') def get_parties(self,request): current_user = endpoints.get_current_user() keywords = [] party_list = [] keywords.append(request.name) party_query = Party_.query(Party_.name.IN(keywords)) if party_query.get(): if request.offset > 10: for party in party_query.fetch(10,offset=request.offset): party_list.append(Party_class(name= request.party_name)) return Party_list(Parties = party_list) #if we are only pulling the first ten Parties else: for party in party_query.fetch(10): party_list.append(Party_class(name= party.name)) count = len(party_list) return Party_list(Parties = party_list) else: party_list = [] party_list.append(Party_class(name = 'None', pass_code = 'None')) count = 0 return Party_list(Parties = party_list) @endpoints.method(Song_class,add_response, path='authed_play',http_method='POST', name='pocketjuke.playAuthed') def play_song(self,request): """Set Play song Flag""" 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(): song = song_query.get() if not song.played: song.played = True; song.put() #delete all the activities for that song in that party activity_query = Activity.query(Activity.song == song.key,Activity.party_key == user.party_key).fetch(keys_only=True) ndb.delete_multi(activity_query) return add_response(response = 'Song has been updated') else: return add_response(response = 'song not found') @endpoints.method(Song_class,add_response, path='authed_stop',http_method='POST', name='pocketjuke.stopAuthed') def stop_song(self,request): """Unmarks the palying song so it can be voted on""" 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(): song = song_query.get() if song.played: song.played = False; song.put() return add_response(response = 'Song has been updated') else: return add_response(response = 'song not found') @endpoints.method(message_types.VoidMessage,add_response, path='auted_leaveParty',http_method='GET', name='pocketjuke.leavePartyAuthed') def leave_Party(self,request): current_user = endpoints.get_current_user() active_user = User.query(User.user_id == current_user.user_id()) user = active_user.get() party = user.party_key.get() party.attending = party.attending - 1 party.put() user.party_key = None user.put() return add_response(response="Removed from the party") @endpoints.method(Party_class,add_response, path='authed_joinParty',http_method='POST', name='pocketjuke.joinPartyAuthed') def join_Party(self,response): current_user = endpoints.get_current_user() keywords = [] keywords.append(response.name) party_query = Party_.query(Party_.name.IN(keywords)) if party_query.get(): user_query = User.query(User.user_id == current_user.user_id()) user = user_query.get() party = party_query.get() #party.attending = party.attending + 1 #party_query = Party_.query(Party_.name.IN(keywords)) user.party_key = party.put() user.put() return add_response(response="Joined party") else: return add_response(response="Unable to Join Party") @endpoints.method(Song_class,add_response, path='authed_addSong',http_method='POST', name='pocketjuke.addSongAuthed') def add_song(self,request): current_user = endpoints.get_current_user() user_query = User.query(User.user_id == current_user.user_id()) user = user_query.get() party_query = user.party_key.get() song_query = Song.query(ndb.AND(Song.track_id == request.track_id,Song.party_key == user.party_key)) if not song_query.get(): 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')
test_file = os.path.join(pwd, 'testdata', 'discovery', filename) with open(test_file) as f: return json.loads(f.read()) except IOError as e: print 'Could not find expected output file ' + test_file raise e class Foo(messages.Message): name = messages.StringField(1) value = messages.IntegerField(2, variant=messages.Variant.INT32) FooCollection = make_collection(Foo) FooResource = endpoints.ResourceContainer( Foo, id=messages.StringField(1, required=True), ) FooIdResource = endpoints.ResourceContainer( message_types.VoidMessage, id=messages.StringField(1, required=True), ) FooNResource = endpoints.ResourceContainer( message_types.VoidMessage, n=messages.IntegerField(1, required=True, variant=messages.Variant.INT32), ) @endpoints.api(name='foo', version='v1', audiences=['audiences'], title='The Foo API',
""" Request containers for the project tag API """ import endpoints from protorpc import messages as api_messages from .messages import (GlobalTagRequestMessage, MoveTagRequestMessage) ProjectIDContainer = endpoints.ResourceContainer( api_messages.Message, project_id=api_messages.IntegerField(2, variant=api_messages.Variant.INT32)) ProjectTagIDContainer = endpoints.ResourceContainer( api_messages.Message, project_id=api_messages.IntegerField(2, variant=api_messages.Variant.INT32), project_tag_id=api_messages.IntegerField( 3, variant=api_messages.Variant.INT32)) PutProjectTagContainer = endpoints.ResourceContainer( GlobalTagRequestMessage, project_id=api_messages.IntegerField(2, variant=api_messages.Variant.INT32), project_tag_id=api_messages.IntegerField( 3, variant=api_messages.Variant.INT32), ) CreateProjectTagContainer = endpoints.ResourceContainer( GlobalTagRequestMessage, project_id=api_messages.IntegerField(2, variant=api_messages.Variant.INT32), ) MoveProjectTagContainer = endpoints.ResourceContainer(
""" conference.py -- Udacity conference server-side Python App Engine API; uses Google Cloud Endpoints, Extended the provided code and added new methods/Endpoints $Id: conference.py,v 1 2016/01/03 Zeeshan Ahamd Author: Zeeshan Ahmad Email: [email protected] """ __author__ = '[email protected] (Zeeshan Ahmad)' CONF_GET_REQUEST = endpoints.ResourceContainer( message_types.VoidMessage, websafeConferenceKey=messages.StringField(1), ) SESSION_GET_REQUEST = endpoints.ResourceContainer( message_types.VoidMessage, websafeSessionKey=messages.StringField(1), ) SPEAKER_GET_REQUEST = endpoints.ResourceContainer( message_types.VoidMessage, websafeSpeakerKey=messages.StringField(1), ) EMAIL_SCOPE = endpoints.EMAIL_SCOPE API_EXPLORER_CLIENT_ID = endpoints.API_EXPLORER_CLIENT_ID DEFAULTS = { "city": "Default City",
from models import StringMessage, NewGameForm, GameForm, MakeMoveForm,\ ScoreForms from utils import get_by_urlsafe # NEW_GAME_REQUEST = endpoints.ResourceContainer(NewGameForm) # GET_GAME_REQUEST = endpoints.ResourceContainer( # urlsafe_game_key=messages.StringField(1),) # MAKE_MOVE_REQUEST = endpoints.ResourceContainer( # MakeMoveForm, # urlsafe_game_key=messages.StringField(1),) # USER_REQUEST = endpoints.ResourceContainer(user_name=messages.StringField(1), # email=messages.StringField(2)) START_GAME = endpoints.ResourceContainer(game_id=messages.StringField(1), player1=messages.StringField(2), player2=messages.StringField(3)) GAME_ID = endpoints.ResourceContainer(game_id=messages.StringField(1)) MAKE_NEXT_MOVE_REQUEST = endpoints.ResourceContainer( x=messages.IntegerField(1), y=messages.IntegerField(2), user_id=messages.StringField(3), game_id=messages.StringField(4)) MEMCACHE_MOVES_REMAINING = 'MOVES_REMAINING' @endpoints.api(name='guess_a_number', version='v1') class GuessANumberApi(remote.Service):
class GreetingApi(remote.Service): @endpoints.method( # This method does not take a request message. message_types.VoidMessage, # This method returns a GreetingCollection message. GreetingCollection, path='greetings', http_method='GET', name='greetings.list') def list_greetings(self, unused_request): return STORED_GREETINGS # ResourceContainers are used to encapsuate a request body and url # parameters. This one is used to represent the Greeting ID for the # greeting_get method. GET_RESOURCE = endpoints.ResourceContainer( # The request body should be empty. message_types.VoidMessage, # Accept one url parameter: an integer named 'id' id=messages.IntegerField(1, variant=messages.Variant.INT32)) @endpoints.method( # Use the ResourceContainer defined above to accept an empty body # but an ID in the query string. GET_RESOURCE, # This method returns a Greeting message. Greeting, # The path defines the source of the URL parameter 'id'. If not # specified here, it would need to be in the query string. path='greetings/{id}', http_method='GET', name='greetings.get') def get_greeting(self, request): try: # request.id is used to access the URL parameter. return STORED_GREETINGS.items[request.id] except (IndexError, TypeError): raise endpoints.NotFoundException( 'Greeting {} not found'.format(request.id)) # [END greeting_api] # [START multiply] # This ResourceContainer is similar to the one used for get_greeting, but # this one also contains a request body in the form of a Greeting message. MULTIPLY_RESOURCE = endpoints.ResourceContainer( Greeting, times=messages.IntegerField(2, variant=messages.Variant.INT32, required=True)) @endpoints.method( # This method accepts a request body containing a Greeting message # and a URL parameter specifying how many times to multiply the # message. MULTIPLY_RESOURCE, # This method returns a Greeting message. Greeting, path='greetings/multiply/{times}', http_method='POST', name='greetings.multiply') def multiply_greeting(self, request): return Greeting(message=request.message * request.times)
class ChessApi(remote.Service): """chess.cf API v1.""" @classmethod def get_user_from_token(cls, token): tokenObj = auth_models.UserToken.get(subject='api', token=token) if not tokenObj: return None userObj = ndb.Key(Account, int(tokenObj.user)).get() return userObj login_request = endpoints.ResourceContainer( message_types.VoidMessage, username=messages.StringField(1, required=True), password=messages.StringField(2, required=True)) token_request = endpoints.ResourceContainer(message_types.VoidMessage, token=messages.StringField( 1, required=True)) token_uid_request = endpoints.ResourceContainer( message_types.VoidMessage, token=messages.StringField(1, required=True), uid=messages.IntegerField(2, required=True)) newGame_request = endpoints.ResourceContainer( message_types.VoidMessage, token=messages.StringField(1, required=True), color=messages.StringField(2, required=True), opponent=messages.StringField(3, required=True), friend=messages.IntegerField(4)) gameMove_request = endpoints.ResourceContainer( message_types.VoidMessage, token=messages.StringField(1, required=True), uid=messages.IntegerField(2, required=True), move=messages.StringField(3, required=True)) friends_search_request = endpoints.ResourceContainer( message_types.VoidMessage, token=messages.StringField(1, required=True), query=messages.StringField(2, required=True)) friends_request_response_request = endpoints.ResourceContainer( message_types.VoidMessage, token=messages.StringField(1, required=True), uid=messages.IntegerField(2, required=True), action=messages.StringField(3, required=True)) @endpoints.method(login_request, LoginResponse, path='login', http_method='GET', name='user.login') def login(self, request): try: user = Account.get_by_auth_password( 'lower:' + request.username.lower(), request.password) token = Account.token_model.create(user.key.id(), 'api') response = LoginResponse(token=token.token, username=user.username()) return response except (InvalidAuthIdError, InvalidPasswordError), e: raise endpoints.UnauthorizedException('WRONG_LOGIN')
class TestPlanApi(remote.Service): """A handler for Test Plan API.""" @base.ApiMethod(endpoints.ResourceContainer(message_types.VoidMessage), mtt_messages.TestPlanList, path='/test_plans', http_method='GET', name='list') def List(self, request): """Lists test plans.""" test_plans = list(ndb_models.TestPlan.query().order( ndb_models.TestPlan.name)) test_plan_msgs = mtt_messages.ConvertList(test_plans, mtt_messages.TestPlan) return mtt_messages.TestPlanList(test_plans=test_plan_msgs) @base.ApiMethod(endpoints.ResourceContainer(mtt_messages.TestPlan), mtt_messages.TestPlan, path='/test_plans', http_method='POST', name='create') def Create(self, request): """Creates a test plan. Body: Test plan data """ test_plan = mtt_messages.Convert(request, ndb_models.TestPlan, from_cls=mtt_messages.TestPlan) _ValidateTestPlan(test_plan) test_plan.key = None test_plan.put() test_scheduler.ScheduleTestPlanCronJob(test_plan.key.id()) return mtt_messages.Convert(test_plan, mtt_messages.TestPlan) @base.ApiMethod(endpoints.ResourceContainer( message_types.VoidMessage, test_plan_id=messages.StringField(1, required=True)), mtt_messages.TestPlan, path='{test_plan_id}', http_method='GET', name='get') def Get(self, request): """Fetches a test plan. Parameters: test_plan_id: Test plan ID, or zero for an empty test plan """ if request.test_plan_id == '0': # For ID 0, return an empty test plan object to use as a template in UI. test_plan = ndb_models.TestPlan(id=0, name='') else: test_plan = mtt_messages.ConvertToKey(ndb_models.TestPlan, request.test_plan_id).get() if not test_plan: raise endpoints.NotFoundException('No test plan with ID %s' % request.test_plan_id) return mtt_messages.Convert(test_plan, mtt_messages.TestPlan) @base.ApiMethod(endpoints.ResourceContainer( mtt_messages.TestPlan, test_plan_id=messages.StringField(1, required=True)), mtt_messages.TestPlan, path='{test_plan_id}', http_method='PUT', name='update') def Update(self, request): """Updates a test plan. Body: Test plan data Parameters: test_plan_id: Test plan ID """ test_plan_key = mtt_messages.ConvertToKey(ndb_models.TestPlan, request.test_plan_id) if not test_plan_key.get(): raise endpoints.NotFoundException() test_plan = mtt_messages.Convert(request, ndb_models.TestPlan, from_cls=mtt_messages.TestPlan) _ValidateTestPlan(test_plan) test_plan.key = test_plan_key test_plan.put() test_scheduler.ScheduleTestPlanCronJob(test_plan.key.id()) return mtt_messages.Convert(test_plan, mtt_messages.TestPlan) @base.ApiMethod(endpoints.ResourceContainer( message_types.VoidMessage, test_plan_id=messages.StringField(1, required=True)), message_types.VoidMessage, path='{test_plan_id}', http_method='DELETE', name='delete') def Delete(self, request): """Deletes a test plan. Parameters: test_plan_id: Test plan ID """ test_plan_key = mtt_messages.ConvertToKey(ndb_models.TestPlan, request.test_plan_id) test_plan_key.delete() return message_types.VoidMessage() @base.ApiMethod(endpoints.ResourceContainer( message_types.VoidMessage, test_plan_id=messages.StringField(1, required=True)), message_types.VoidMessage, path='{test_plan_id}/run', http_method='POST', name='run') def Run(self, request): """Runs a test plan immediately. Parameters: test_plan_id: Test plan ID """ test_plan = mtt_messages.ConvertToKey(ndb_models.TestPlan, request.test_plan_id).get() if not test_plan: raise endpoints.NotFoundException('Test plan %s does not exist' % request.test_plan_id) if not test_plan.test_run_configs: raise endpoints.BadRequestException( 'No test run configs with ID %s' % request.test_plan_id) test_plan_kicker.KickTestPlan(test_plan.key.id()) # TODO: returns a test plan job object. return message_types.VoidMessage()
'TOPIC': 'topics', 'MONTH': 'month', 'MAX_ATTENDEES': 'maxAttendees', } SESSIONFIELDS = { 'NAME': 'name', 'TYPEOFSESSION': 'session_type', 'SPEAKERNAME': 'speaker_name', 'STARTTIME': 'start_time', 'DURATION': 'duration', 'LOCATION': 'location', } CONF_GET_REQUEST = endpoints.ResourceContainer( message_types.VoidMessage, websafeConferenceKey=messages.StringField(1), ) CONF_POST_REQUEST = endpoints.ResourceContainer( ConferenceForm, websafeConferenceKey=messages.StringField(1), ) SPEAKER_REQUEST = endpoints.ResourceContainer( message_types.VoidMessage, websafeConferenceKey=messages.StringField(1), ) WISHLIST_REQUEST = endpoints.ResourceContainer( message_types.VoidMessage, sessionKey=messages.IntegerField(1),
import endpoints from google.appengine.ext import ndb from resources.users import ApiUser, ApiUsers, User from protorpc import messages, message_types, remote from apis.base import api_holder from resources.countries import Country import httplib class ConflictException(endpoints.ServiceException): """Conflict exception that is mapped to a 409 response.""" http_status = httplib.CONFLICT NameResource = endpoints.ResourceContainer( message_types.VoidMessage, id=messages.IntegerField(1), ) CountryResource = endpoints.ResourceContainer( message_types.VoidMessage, country=messages.StringField(1) ) @api_holder.api_class(resource_name='Users',path='users') class Users_Service(remote.Service): @endpoints.method( ApiUser, ApiUser, path="add", http_method="PUT", name="create", )
__author__ = 'brendan' import endpoints from protorpc import message_types from protorpc import messages from google.appengine.ext import ndb DEBUG = True USER_AUTH_RC = endpoints.ResourceContainer( message_types.VoidMessage, email=messages.StringField(1, required=True), password=messages.StringField(2, required=True)) USER_RC = endpoints.ResourceContainer( message_types.VoidMessage, user_id=messages.IntegerField(1, required=True), user_token=messages.StringField(2, required=True), last_cursor=messages.StringField(3, required=False), school_type=messages.StringField(4, required=False), college_rank=messages.StringField(5, required=False)) USER_NEW_RC = endpoints.ResourceContainer( message_types.VoidMessage, email=messages.StringField(1, required=True), first_name=messages.StringField(2, required=True), last_name=messages.StringField(3, required=True), phone=messages.StringField(4, required=True), school_type=messages.StringField(5, required=True)) def get_stripe_api_key(): if DEBUG: return "sk_test_5sR4GHddXZ1EK8kQ98t5Heuw"
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Host Info APIs implemented using Google Cloud Endpoints.""" import datetime import endpoints from protorpc import remote from google.appengine.api import users from webapp.src import vtslab_status as Status from webapp.src.proto import model HOST_INFO_RESOURCE = endpoints.ResourceContainer(model.HostInfoMessage) # Product type name for null device. _NULL_DEVICE_PRODUCT_TYPE = "null" def AddNullDevices(hostname, null_device_count): """Adds null devices to DeviceModel data store. Args: hostname: string, the host name. null_device_count: integer, the number of null devices. """ device_query = model.DeviceModel.query( model.DeviceModel.hostname == hostname, model.DeviceModel.product == _NULL_DEVICE_PRODUCT_TYPE)
from models import ConferenceQueryForm from models import ConferenceQueryForms from models import Session from models import SessionForm from models import SessionForms from models import BooleanMessage from models import ConflictException from google.appengine.api import memcache from models import StringMessage from google.appengine.api import taskqueue CONF_GET_REQUEST = endpoints.ResourceContainer( message_types.VoidMessage, websafeConferenceKey=messages.StringField(1), ) SESSION_GET_REQUEST = endpoints.ResourceContainer( SessionForm, websafeConferenceKey=messages.StringField(1), ) SESSION_BY_TYPE = endpoints.ResourceContainer( message_types.VoidMessage, websafeConferenceKey=messages.StringField(1), typeOfSession=messages.StringField(2)) SESSION_BY_SPEAKER = endpoints.ResourceContainer( message_types.VoidMessage, speaker=messages.StringField(1),