示例#1
0
def api_document_put(document_name, document_id):
    '''Make changes to an existing document and save it to the database'''
    user = helpers.user_required(1)
    model = models.model_get(document_name)

    # get the dictionary of arguments
    args = flask.request.get_json()

    # get the document
    document = None
    try:
        document = model.objects.get(id=document_id)
    except mongoengine.errors.ValidationError:
        return helpers.api_error(message='No document found', code=404)

    # iterate through the args and screen them
    if args:
        for arg_name in args:
            print('PROCESSING ARG_NAME', arg_name)
            print('VALUE', args[arg_name])

    # update the document and return a success
    document.update(**args)
    document.reload()
    if document._after_put(user):
        document.save()
    return helpers.api_success(message='Document updated.')
示例#2
0
def api_document_post(document_name):
    '''Create a new document and insert it into the database'''
    user = helpers.user_required(1)
    model = models.model_get(document_name)

    # get the dictionary of arguments
    args = flask.request.get_json()

    # filter out fields based on access level
    try:
        for field_name in model._blacklist_postput[user.access]:
            args.pop(field_name, None)
    except IndexError:
        pass

    # some types need extra processing (e.g., datetime fields)
    model_fields = model._fields
    for arg_name in args:
        value = args[arg_name]
        if isinstance(model_fields.get(arg_name, None), mongoengine.fields.DateTimeField):
            args[arg_name] = dateutil.parser.parse(value)

    # put together the new document
    new = model(**args)

    # some models need special handling, so make sure to call the 'after' func
    new._after_post(user)

    # now save it and return it
    new.save()
    return helpers.api_success(data=new)
示例#3
0
def api_document_delete(document_name, document_id):
    """Delete an existing document from the database"""
    user = helpers.user_required(1)
    model = models.model_get(document_name)

    # get the document
    document = None
    try:
        document = model.objects.get(id=document_id)
    except mongoengine.errors.ValidationError:
        return helpers.api_error(message='No document found', code=404)

    # delete it!
    document.delete()
    return helpers.api_success(message='Document deleted.')
示例#4
0
def api_document_get_by_id(document_name, document_id):
    """Get one specific document instance from an ID"""
    user = helpers.user_get()
    model = models.model_get(document_name)
    return helpers.api_success(data=model.objects.get(id=document_id))
示例#5
0
def api_document_get(document_name):
    '''Query the database'''
    user = helpers.user_get()
    model = models.model_get(document_name)

    # filter the args
    args_listable = ['__order', '__field']
    args_query = {}
    args_other = {}
    args = flask.request.args
    for arg_name in args:
        if arg_name.startswith('__'):
            if arg_name in args_listable:
                args_other[arg_name] = args.getlist(arg_name)
            else:
                args_other[arg_name] = args[arg_name]
        else:
            args_query[arg_name] = args[arg_name]

    # convert booleans
    model_fields = model._fields
    for arg_name in args_query:
        value = args_query[arg_name]
        if isinstance(model_fields.get(arg_name, None), mongoengine.fields.BooleanField):
            if value == 'true':
                args_query[arg_name] = True
            elif value == 'false':
                args_query[arg_name] = False
            else:
                raise ValueError('you dun fuked up')
            # args_query[arg_name] = True if value == 'true' else False

    # get the ball rolling, so to speak
    query = model.objects(**args_query)

    # We have to establish the access level of the user
    access_level = None

    # Check for anonymity, because anons won't have access fields
    if user.is_anonymous:
        access_level = 0
    else:
        access_level = user.access

    # Exclude the blacklisted fields
    for field_name in model._blacklist_get.get(access_level, []):
        query = query.exclude(field_name)

    # sort the query if applicable
    if '__order' in args_other:
        query = query.order_by(*args_other['__order'])

    # limit the results
    offset = int(args_other.get('__offset', 0))
    if offset:
        query = query.skip(offset)
    length = int(args_other.get('__length', 32))
    query = query.limit(length)

    # perform a text search if necessary
    if '__search' in args_other:
        query = query.search_text(args_other['__search'])

    # filter out unwanted fields
    if '__field' in args_other:
        query = query.scalar(*args_other['__field'])

    # return the results
    # return helpers.api_success(list(query))
    return helpers.api_success(data={
        'list': list(query),
        'count': query.count()
    })