示例#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