def postIatResults(): # Try to get json content jsonPayload = flask.request.get_json() if jsonPayload is None: raise BadRequest( "It seems that you're sending me some unexpected data format!") # Check json payload content if jsonPayload.get("results", None) is None or jsonPayload.get( "order", None) is None: raise BadRequest("That is an invalid json payload!") # Check session if session.get("user_id", None) is None: raise ApiException( "There is not a valid session cookie in this request!") # Try to update user access info user_id = session.get("user_id") DBShortcuts.updateLastUserView("iat_final", user_id) # Try to insert user results MongoConnection = MongoConnector(MONGO_DB, MONGO_RESULTS_COLLECTION, MONGO_URI) insertResults = MongoConnection.collection.insert_one({ "user_id": user_id, "timestamp": datetime.datetime.utcnow(), "results": jsonPayload.get("results"), "order": jsonPayload.get("order") }) # Check insert operations if not insertResults.acknowledged: raise ApiException( "Something went wrong while updating the user info or inserting his/her results!" ) # Close pymongo connection MongoConnection.close() # Send Response newResponse = ApiResponse("Ok!") return newResponse.response
def hello_world(): newResponse = ApiResponse( "Hello World! (This means that the API is up and running)") return newResponse.response
def InternalServerErrorHandler(e): errorResponse = ApiResponse({}, 500, True, str(e)) return errorResponse.response
def ApiErrorHandler(e): errorResponse = ApiResponse({}, e.status_code, True, str(e)) return errorResponse.response
def postDebugSurvey(): # Try to get json content jsonPayload = flask.request.get_json() if jsonPayload is None: raise BadRequest( "It seems that you're sending me some unexpected data format!") # Check session if session.get("user_id", None) is None: raise ApiException( "There is not a valid session cookie in this request!") # Before anything, let's check the Captcha # Get captcha response googleCapthca = jsonPayload.get("g", None) if googleCapthca is None or googleCapthca == "": logger.warning("Captcha validation failed. Empty captcha response") raise ApiException( "Well, if you don't send a valid reCaptcha, I'll think you're a robot!" ) # Ask Google if we have a valid captcha logger.info("Validating captcha with Google service...") response = requests.post( "https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}" .format(RECAPTCHA_PRIVATE, googleCapthca)) # Parse response as JSON try: responseAsJson = response.json() except Exception: logger.warning( "Captcha validation failed. Received an invalid response format from Google" ) raise ApiException( "This is embarrasing. I could not ask Google if you're indeed a human!" ) # Is the user a human? human = responseAsJson.get("success", None) if human is None or not human: logger.warning( "Captcha validation failed. Google didn't acknowledged the captcha value" ) raise ApiException("Get out of here, you filthy robot!") # Clean request payload for key in jsonPayload: if jsonPayload[key] == "" or jsonPayload[key] == "NONE": jsonPayload[key] = None # Get user id user_id = session.get("user_id") # Open DB connection MongoConnection = MongoConnector(MONGO_DB, MONGO_DEBUG_SURVEY_COLLECTION, MONGO_URI) # Check if user_id is already registered in survey searchResults = MongoConnection.collection.count_documents( {"user_id": user_id}) if searchResults > 0: # Log warning logger.warning( "User {0} from {1} tried to re submit survey answers.".format( user_id, request.remote_addr)) # Return API newResponse = ApiResponse( "User already answered the survey! POST payload will be ignored.") return newResponse.response # Insert user survey responses insertResults = MongoConnection.collection.insert_one({ "user_id": user_id, "timestamp": datetime.datetime.utcnow(), "suggestions": jsonPayload["srvy_suggestions"], "felt": jsonPayload["srvy_felt"], "result": jsonPayload["srvy_result"] }) # Close connection MongoConnection.close() # Check insert if not insertResults.acknowledged: raise ApiException("Something went while updating the Survey table!") newResponse = ApiResponse("Ok!") return newResponse.response
def getStimuli(): # Get test stage stage = flask.request.args.get('stage', None) # If there's not an stage, send error if stage is None: raise BadRequest( "Well... if you don't tell me your stage, how am I supposed to send back some stimuli?" ) # Check if stage can be coerced into a integer try: stage = int(stage) except: raise BadRequest( "Mmm... I'm starting to suspect that you don't know what you're supposed to send" ) # Define data if stage == 1: # Choose random images imageList = list() # Create two permutations of imagelist imageList_1 = STIMULI_IMAGES imageList_2 = STIMULI_IMAGES random.shuffle(imageList_1) random.shuffle(imageList_2) imageList.extend(imageList_1) imageList.extend(imageList_2) finalList = imageList elif stage == 2: # Choose random words wordList = STIMULI_WORDS random.shuffle(wordList) finalList = wordList elif stage >= 3 and stage < 5: # Choose random words wordList = STIMULI_WORDS random.shuffle(wordList) # Choose random images imageList = list() # Create two permutations of imagelist imageList_1 = STIMULI_IMAGES imageList_2 = STIMULI_IMAGES random.shuffle(imageList_1) random.shuffle(imageList_2) imageList.extend(imageList_1) imageList.extend(imageList_2) # Create an empty list mergedList = [None] * (len(wordList) + len(imageList)) # Fill every other element with a word mergedList[::2] = wordList # Fill every other element with an image mergedList[1::2] = imageList # Concatenate train words with merged list finalList = mergedList elif stage == 5: # Choose random images imageList = list() # Create two permutations of imagelist imageList_1 = STIMULI_IMAGES imageList_2 = STIMULI_IMAGES random.shuffle(imageList_1) random.shuffle(imageList_2) imageList.extend(imageList_1) imageList.extend(imageList_2) finalList = imageList elif stage >= 6 and stage < 8: # Choose random words wordList = STIMULI_WORDS random.shuffle(wordList) # Choose random images imageList = list() # Create two permutations of imagelist imageList_1 = STIMULI_IMAGES imageList_2 = STIMULI_IMAGES random.shuffle(imageList_1) random.shuffle(imageList_2) imageList.extend(imageList_1) imageList.extend(imageList_2) # Create an empty list mergedList = [None] * (len(wordList) + len(imageList)) # Fill every other element with a word mergedList[::2] = wordList # Fill every other element with an image mergedList[1::2] = imageList # Concatenate train words with merged list finalList = mergedList else: raise BadRequest( "Well... I don't know what are you expecting me to send in that stage!" ) # Define response data responseData = {"stimuli": finalList} # Send response newResponse = ApiResponse(responseData) return newResponse.response