from server import app import json name = 'Tourney' version = '0.9.7' class about: def on_get(self, req, resp): data = {"name": name, "version": version} resp.body = json.dumps(data) app.add_route('/about', about())
transaction.abort() return None def getById(self, id): try: tournament = next((tournament for tournament in self.list if tournament.id == id), None) if tournament: tournament.ensureLoaded() return tournament except StopIteration as stopIteration: print(stopIteration) return None except ValueError as valueError: print(valueError) return None class tournamentsRoute: def on_get(self, request, response): print('Loading Tournaments') connection = tourneyDatabase.tourneyDatabase() try: email = googleAuthentication.getAuthenticatedEmail(request.headers) print('Email: ' + str(email)) tournaments = connection.tournaments tournaments.ensureLoaded() response.text = tournaments.toJson(email, request.params.get('admin', 0) == '1') finally: connection.close() app.add_route('/data/tournaments', tournamentsRoute())
def get_content_type(self, filename): if filename.endswith('.css'): return 'text/css' elif filename.endswith('.js'): return 'application/javascript' elif filename.endswith('.svg'): return 'image/svg+xml' return 'text/html' def on_get(self, request, response, filename, **kwargs): # todo: some sanity check on the filename path = self.folder + '/' + filename response.status = falcon.HTTP_200 response.cache_control = ['no-cache'] response.content_type = self.get_content_type(filename) response.stream = open(path, 'rb') app.add_route('/external/{filename}', static('external')) app.add_route('/html/{filename}', static('html')) app.add_route('/html/{filename}/{icon}', static('html')) # To handle SVG Suffix app.add_route('/views/{filename}', static('views')) class index: def on_get(self, request, response): path = 'html/index.html' response.status = falcon.HTTP_200 response.cache_control = ['no-cache'] response.content_type = 'text/html' response.stream = open(path, 'rb') app.add_route('/', index())
from server import app import json from utilities import googleAuthentication class authentication: def on_get(self, request, response): print('Checking Authentication') info = googleAuthentication.getAuthenticatedInfoFromHeaders( request.headers) if info: email = info.get('email', None) print('Email: ' + email) response.text = 'OK ' + email else: response.text = 'Error' class authentication_jwt: def on_get(self, request, response): print('Checking Authentication') info = googleAuthentication.getAuthenticatedInfoFromHeaders( request.headers) if info: response.text = json.dumps(info) else: response.text = 'Error' app.add_route('/authentication', authentication()) app.add_route('/authentication/jwt', authentication_jwt())
game.ensureLoadedEventLog() history_game = game.get_game_history(version) json.dumps(history_game) # force data to load history_events = history_game['game']['eventLog'] for attempt in transaction.manager.attempts(): with attempt: game.clearEventLog(False) for event in history_events: eventItem = game.addLogEvent( event.time, event.eventType, event.team, event.player, event.notes) eventItem.teamOriginal = event.teamOriginal transaction.commit() print('Game Revision Restored') #response.text = 'OK' finally: connection.close() app.add_route( '/data/tournament/{id}/date/{dateId}/pitch/{pitchId}/game/{gameId}', GameRoute()) app.add_route( '/data/tournament/{id}/date/{dateId}/pitch/{pitchId}/game/{gameId}/history/{version}', GameHistoryRoute())
transaction.commit() finally: connection.close() class GameTimePasteNameRoute: def on_put(self, request, response, id, dateId, pitchId): body = json.loads(request.stream.read()) connection = tourneyDatabase.tourneyDatabase() try: pitch = Pitch.getPitch(response, connection, id, dateId, pitchId)[2] if pitch: for attempt in transaction.manager.attempts(): with attempt: pitch.name = body['clipboardText'] transaction.commit() finally: connection.close() app.add_route('/data/tournament/{id}/date/{dateId}/pitch/{pitchId}/paste', PitchPasteRoute()) app.add_route('/data/tournament/{id}/date/{dateId}/pitch/{pitchId}/editname', PitchEditNameRoute()) app.add_route( '/data/tournament/{id}/date/{dateId}/pitch/{pitchId}/pastegametimes', GameTimePasteRoute()) app.add_route( '/data/tournament/{id}/date/{dateId}/pitch/{pitchId}/cleargametimes', GameTimeClearRoute())
if not valueName in item: item[valueName] = 0 if value != None: item[valueName] = item[valueName] + value def sort(self): self.grades.sort(key=lambda grade: grade.name) for grades in self.grades: grades.items.sort(key=lambda teamPlayer: teamPlayer.values.get('goals', 0), reverse=True) grades.cards.sort(key=lambda card: (card.team, card.player), reverse=False) class playerStatisticsRoute: cache = {} def on_get(self, request, response, id): connection = tourneyDatabase.tourneyDatabase() try: email = googleAuthentication.getAuthenticatedEmail(request.headers) tournament = connection.tournaments.getByShortId(id) if tournament: statistics = PlayerStatistics(tournament) statistics.calculate() statistics.sort() result = statistics.toJsonObject() result['canEdit'] = tournament.canEdit(email) response.text = json.dumps(result) finally: connection.close() app.add_route('/data/tournament/{id}/playerstatistics', playerStatisticsRoute())
finally: connection.close() class PitchRoute: def on_put(self, request, response, id, dateId): connection = tourneyDatabase.tourneyDatabase() try: date = GameDate.getGameDate(response, connection, id, dateId)[1] if date: for attempt in transaction.manager.attempts(): with attempt: date.addPitch() transaction.commit() finally: connection.close() def on_delete(self, request, response, id, dateId): connection = tourneyDatabase.tourneyDatabase() try: date = GameDate.getGameDate(response, connection, id, dateId)[1] if date: for attempt in transaction.manager.attempts(): with attempt: date.deleteLastPitch() transaction.commit() finally: connection.close() app.add_route('/data/tournament/{id}/date/{dateId}', DateRoute()) app.add_route('/data/tournament/{id}/date/{dateId}/times/paste', GameTimePasteRoute()) app.add_route('/data/tournament/{id}/date/{dateId}/pitch', PitchRoute())
try: email = googleAuthentication.getAuthenticatedEmail(request.headers) tournament = connection.tournaments.getByShortId(id) if tournament: #if not tournament._v_modified and tournament.id in statisticsRoute.cache: # result = statisticsRoute.cache[tournament.id] #else: statistics = Statistics(tournament) statistics.calculate() statistics.sort() result = statistics.toJsonObject() #statisticsRoute.cache[tournament.id] = result result['canEdit'] = tournament.canEdit(email) response.text = json.dumps(result) finally: connection.close() def on_put(self, request, response, id): body = json.loads(request.stream.read()) connection = tourneyDatabase.tourneyDatabase() try: tournament = connection.tournaments.getByShortId(id) if tournament: tournament.updateTeamNames(body['group'], body['revert']) finally: connection.close() app.add_route('/data/tournament/{id}/statistics', statisticsRoute())
from starlette.graphql import GraphQLApp from fastapi import Request, Response, HTTPException from fastapi.security.http import HTTPBearer from authorization import init_enforcer from server import app, get_current_user from api_graphql.schema import schema @app.middleware("http") async def add_current_user(request: Request, call_next): # Only do the following if this is the graphql app. if request.url.path.startswith("/graphql") and request.method != "OPTIONS": try: request.state.user = await get_current_user(await HTTPBearer() (request)) request.state.enforcer = init_enforcer() except HTTPException as ex: return Response(ex.detail, media_type="text/plain", status_code=ex.status_code) return await call_next(request) app.add_route("/graphql", GraphQLApp(schema=schema))
connection = tourneyDatabase.tourneyDatabase() try: tournament = connection.tournaments.getById(body['id']) if not tournament: tournament = Tournament(body['id']) for attempt in transaction.manager.attempts(): with attempt: connection.tournaments.addTournament(tournament) transaction.commit() for attempt in transaction.manager.attempts(): with attempt: tournament.assign(body) transaction.commit() finally: connection.close() class tournamentAddDateRoute: def on_put(self, request, response, id): connection = tourneyDatabase.tourneyDatabase() try: tournament = connection.tournaments.getByShortId(id) if tournament: tournament.addDate() finally: connection.close() app.add_route('/data/tournament/{id}', tournamentIdRoute()) app.add_route('/data/tournament/', tournamentRoute()) app.add_route('/data/tournament/{id}/adddate', tournamentAddDateRoute())