Esempio n. 1
0
def api_start_lexeme_collection():
    """
    endpoint for inserting an incomplete lexeme collection into the database
    via POST request
    """

    # Get the starting lexeme and type
    try:
        typ_param = request.form['type']
        start_str = request.form['start']
    except KeyError:
        return 'ERROR: Missing type or starting lexeme', 400

    # Get the initial tag list
    # The assumption is that individual tags cannot contain commas
    try:
        tags = request.form["tags"].split(',')
        if tags == '':
            tags = []
    except KeyError:
        tags = []

    # Validate the initial tag list
    # Tags can only contain alphanumeric characters and spaces
    for tag in tags:
        for char in tag:
            if not (char.isalnum() or char == " "):
                return "ERROR: Tags can only contain alphanumerics or spaces.", 400

    # extract the type parameter (type of lexeme)
    if typ_param == 'sentence':
        typ = 'sentence'
        db_collection = MONGO.db.paragraphs
    else:
        #default is Word
        typ = 'word'
        db_collection = MONGO.db.sentences

    # Strip any whitespace from start_str
    start_str = start_str.strip()

    # Construct start_str as a Lexeme
    if typ == 'word':
        print "Word"
        start_lex = Word(start_str)
    elif typ == 'sentence':
        start_lex = Sentence(start_str)

    # validate it as a beginning lexeme
    if not start_lex.is_valid_beginning():
        print "FAILED"
        return 'ERROR: '+start_lex.get_text()+' is not a valid beginning '+start_lex.type(), 400

    # Insert into the database
    db_collection.insert(
        {"lexemes": [start_lex.get_text()], "complete": False, "tags":tags})

    # return 200 OK
    return "Successfully started the lexeme collection", 200
Esempio n. 2
0
def api_append_to_lexeme_collection():
    """
    endpoint for continuing or completing an incomplete lexeme collection
    In order for this to work, the client must verify that it was the one who
    originally sent the request for the incomplete LC, by passing back the key
    that was sent with it.
    """
    try:
        addition = request.form["addition"]
        key = request.form["key"]
        typ_param = request.form["type"]
    except KeyError:
        return "ERROR: lexeme type, key, or addition is missing", 400

    # Separate try/except for complete because it is not a required parameter
    try:
        complete = request.form["complete"]
    except KeyError:
        complete = 'false'

    # determine whether the user is trying to continue or complete
    # defaults to continue
    if complete == 'true':
        try_to_complete = True
    else:
        try_to_complete = False

    # extract the type parameter (type of lexeme)
    if typ_param == 'sentence':
        typ = 'sentence'
        db_collection = MONGO.db.paragraphs
    else:
        #default is Word
        typ = 'word'
        db_collection = MONGO.db.sentences

    # check that the key is not timed out
    # this assumes that if the key is not in LC_MAP, it has expired
    if not key in LC_MAP:
        return "ERROR: This lexeme collection has timed out", 408

    # strip any whitespace from the new addition
    addition = addition.strip()

    # assume addition is one lexeme; pull it into the appropriate class
    # also make the LexemeCollection for later
    if typ == 'word':
        new_lexeme = Word(addition)
        lexc = WordCollection()
    elif typ == 'sentence':
        new_lexeme = Sentence(addition)
        lexc = SentenceCollection()

    # validate it as an ordinary or ending lexeme, depending on the complete
    # parameter
    if try_to_complete:
        if not new_lexeme.is_valid_end():
            return 'ERROR: '+new_lexeme.get_text()+' is not a valid ending '+new_lexeme.type(), 400
    else:
        if not new_lexeme.is_valid():
            return 'ERROR: '+new_lexeme.get_text()+' is not a valid '+new_lexeme.type(), 400

    # get the document in the database by the key passed in
    lc_bson_to_be_completed = db_collection.find_one({"key":key})

    if lc_bson_to_be_completed is None:
        # this should never happen
        return 'ERROR: No lexeme collection matching your key was found in the db', 500

    # get data from the query result and add in the new lexeme
    lexc.import_json(lc_bson_to_be_completed)
    lexc.append(new_lexeme)

    # validate it if completing the LC
    if try_to_complete and not lexc.validate():
        # with proper validation on all API behaviors this should never happen
        # either
        return 'ERROR: The overall lexeme collection is not valid', 400

    # update the document as being complete and remove the key
    
    if try_to_complete:
        db_collection.insert(
        {"lexemes": lexc.view("string"), 
         "complete": try_to_complete, "tags":lc_bson_to_be_completed['tags']})
        db_collection.remove({"_id": lc_bson_to_be_completed['_id']})
    else:
        db_collection.update(
            {"_id": lc_bson_to_be_completed['_id']},
            {'$set': {"complete":try_to_complete, "lexemes":lexc.view("string")},
             '$unset': {"key": ""}},
            upsert=False)

    # remove it from the timeout list
    del LC_MAP[key]

    # return 200 OK
    return "Successfully appended to the lexeme collection", 200