Esempio n. 1
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))
Esempio n. 2
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()
    })