Exemplo n.º 1
0
def delete_instance(request=False,
                    model=False,
                    lookup_field=False,
                    lookup_value=False):

    if not (request and model and lookup_field and lookup_value):
        return error("Invalid request")

    log_request("delete by", model, lookup_field, lookup_value)

    required_method_type = "POST"
    if not check_method_type(request, required_method_type):
        return invalid_method(required_method_type)

    parsed_body = json.loads(request.body.decode('utf-8'))
    if not parsed_body:
        return False

    if 'api_key' in parsed_body:
        admin = check_api_key(parsed_body['api_key'])
    else:
        admin = False
    if not admin:
        return error('Admin only action')

    instance = find_single_instance(model, lookup_field, lookup_value, admin)
    if not instance:
        return error("Can't find in db.")
    instance.delete()

    return JsonResponse({'success': True})
Exemplo n.º 2
0
def upload_file(request):

    #print("REQUEST")
    print(request)
    #count = 0;
    #count += 1
    #for i in request:
    #  print(i)
    #print('- - - - - - - - ')

    try:
        file_dict = {"upload": request.FILES["file"]}
    except:
        print("NO FILE ERROR")
        return error("No file")

    print("**")
    print(file_dict["upload"])

    upload = Upload(**file_dict)
    upload.save()

    upload_url = upload.upload.url
    response = {
        "status": "Upload complete",
        "url": upload_url,
        "success": True
    }
    return JsonResponse(response, safe=False)
Exemplo n.º 3
0
def parse_non_text_field(field_type, value):
    if field_type == 'BooleanField':
        if value.upper() == 'TRUE':
            return True
        elif value.upper() == 'FALSE':
            return False
        else:
            return error('Boolean field not true or false')
    else:
        return value
Exemplo n.º 4
0
def get_instance(request=False,
                 model=False,
                 lookup_field=False,
                 lookup_value=False):
    if not (request and model and lookup_field and lookup_value):
        return error("Invalid request")

    # Log the request
    log_request('get', model, lookup_field, lookup_value)

    # Limit response to these fields:
    allowed_fields = getattr(model, 'allowed_fields', ['id'])

    # get API Key:
    api_key_qs = request.GET.get('api_key', False)
    if api_key_qs:
        api_key = bleach.clean(api_key_qs)
    else:
        api_key = False

    # Admin True or False based on api_key
    admin = check_api_key(api_key)

    # Check that request uses "GET" method else return error
    required_method_type = "GET"
    if not check_method_type(request, required_method_type):
        return invalid_method(required_method_type)

    # Get single queryset from db else return error
    instance = find_single_instance(model, lookup_field, lookup_value, admin)
    instance_dict = single_instance_to_dict(instance,
                                            request=request,
                                            allowed_fields=allowed_fields)

    if instance_dict:
        response = {
            get_model_name(model, singular=True): instance_dict,
            'admin': admin
        }
        return JsonResponse(response, safe=False)
    else:
        return error("Can't find in db.")
Exemplo n.º 5
0
def new_person(request):
    required_method_type = "POST"
    if not check_method_type(request, required_method_type):
        return invalid_method(required_method_type)

    try:
        parsed_body = json.loads(request.body.decode('utf-8'))
    except:
        return error('no body')

    for field in Person.required_fields:
        if field not in parsed_body:
            return error('mising fields')

    if 'api_key' in parsed_body:
        admin = check_api_key(parsed_body['api_key'])
    else:
        admin = False
    if not admin:
        return error('Admin only action')

    parsed_body['hashed_password'] = bcrypt.hashpw(
        parsed_body['password'].encode('utf-8'), bcrypt.gensalt())
    try:
        del parsed_body['password']
        del parsed_body['api_key']
    except KeyError:
        return error('cant delete')

    person = Person(**parsed_body)
    try:
        person.save()
    except:
        print('ERROR: Can\'t create person.')
        print(sys.exc_info())
        return error('Can\'t create person.')

    return JsonResponse(Person.admin_view(person))
Exemplo n.º 6
0
def new_instance(request=False, model=False):

    if not (request and model):
        return error("Invalid Request")

    log_request("new", model, 'new', '')

    # Limit to/Require these fields:
    allowed_fields = getattr(model, 'allowed_fields', ['id'])
    required_fields = getattr(model, 'required_fields', [])

    required_method_type = "POST"
    if not check_method_type(request, required_method_type):
        return invalid_method(required_method_type)

    parsed_body = json.loads(request.body.decode('utf-8'))
    if not parsed_body:
        return False

    if 'api_key' in parsed_body:
        admin = check_api_key(parsed_body['api_key'])
    else:
        admin = False
    if not admin:
        return error('Admin only action')

    request_dict = check_for_required_and_allowed_fields(
        model, parsed_body, required_fields, allowed_fields)
    if not request_dict:
        return error("Invalid request")

    object_instance = save_object_instance(model, request_dict)
    if not object_instance:
        return error("Error saving object")
    instance_dict = dict_from_single_object(object_instance, allowed_fields)
    instance_dict["success"] = True
    return JsonResponse(instance_dict, safe=False)
Exemplo n.º 7
0
def index_response(request=False, model=False, order_by='?'):

    if not (request and model):
        return error('Invalid request')

    # Log the request
    log_request('get', model, 'index', 'all')

    # Show these fields on index:
    index_fields = getattr(model, 'index_fields', ['id'])

    # get API Key:
    api_key_qs = request.GET.get('api_key', False)
    if api_key_qs:
        api_key = bleach.clean(api_key_qs)
    else:
        api_key = False

    # Admin True or False based on api_key
    admin = check_api_key(api_key)

    # Get queryset of instances for specified or default page
    # Try/except will deal with any non integer values other than 'all'
    try:
        page = int(bleach.clean(request.GET.get('page', str(default['page']))))
        quantity_qs = bleach.clean(
            request.GET.get('quantity', str(default['quantity'])))
        if quantity_qs == 'all':
            end_of_page = None
            start_of_page = None
        else:
            quantity = int(bleach.clean(quantity_qs))
            end_of_page = page * quantity
            start_of_page = end_of_page - quantity
    except ValueError:
        page = default['page']
        quantity = default['quantity']
        end_of_page = page * quantity
        start_of_page = end_of_page - quantity

    # Get all instances from DB
    filter = {}
    if hasattr(model, 'hide_if') and not admin:
        filter[model.hide_if] = False

    # Get other filters from model:
    if hasattr(model, 'allowed_filters'):
        for new_filter in model.allowed_filters:
            filter_qs = ''
            try:
                filter_qs = request.GET.get(new_filter, str(''))
                filter_qs = bleach.clean(filter_qs)
            except:
                pass
            if filter_qs != '':
                if filter_qs.lower() == "false":
                    filter_qs = False
                elif filter_qs.lower() == "true":
                    filter_qs = True
                filter[new_filter] = filter_qs

    ordered_instance_objects_qs = model.objects.filter(
        **filter).order_by(order_by)
    # If not all are requested, scope to quantity and page:
    if (end_of_page != None) and (start_of_page != None):
        ordered_instance_objects_qs = ordered_instance_objects_qs[
            start_of_page:end_of_page]

    # get single instance flow on each object
    modify_each_with = getattr(model, 'index_modify_with', unmodified)
    on_each_instance = partial(single_instance_to_dict,
                               request=request,
                               allowed_fields=index_fields,
                               modify_with=modify_each_with)
    index_list = list(map(on_each_instance, ordered_instance_objects_qs))

    # Get count of items on all pages:
    number_of = model.objects.filter(**filter).count()

    # Create response dict
    model_name = get_model_name(model)
    response = {
        'total_' + model_name: number_of,
        'page': page,
        'admin': admin,
        model_name + '_list': index_list
    }

    # on safe=False: https://stackoverflow.com/questions/28740338/creating-json-array-in-django
    return JsonResponse(response, safe=False)
Exemplo n.º 8
0
def edit_instance(request=False,
                  model=False,
                  lookup_field=False,
                  lookup_value=False):

    if not (request and model and lookup_field and lookup_value):
        return error("Invalid request")

    log_request("edit", model, lookup_field, lookup_value)

    # Limit to/require these fields:
    allowed_fields = getattr(model, 'allowed_fields', ['id'])
    required_fields = getattr(model, 'required_fields', [])

    required_method_type = "POST"
    if not check_method_type(request, required_method_type):
        return invalid_method(required_method_type)

    parsed_body = json.loads(request.body.decode('utf-8'))
    if not parsed_body:
        return False

    if 'api_key' in parsed_body:
        admin = check_api_key(parsed_body['api_key'])
    else:
        admin = False
    if not admin:
        return error('Admin only action')

    ## No required fields because they might not be changing
    request_dict = check_for_required_and_allowed_fields(
        model, parsed_body, [], allowed_fields)
    if not request_dict:
        return error("No body in request or incorrect fields")

    instance = find_single_instance(model, lookup_field, lookup_value, admin)
    if not instance:
        return error("Can't find in db.")

    primary_key_field = model._meta.pk.name
    request_dict[primary_key_field] = instance.pk

    # Update each property in the instance that is different in the request_dict
    for i in request_dict:
        if getattr(instance, i) != request_dict[i]:
            try:
                setattr(instance, i, request_dict[i])
            except:
                return error('Error updating instance')

    # Now check for required_fields
    for i in required_fields:
        if not getattr(instance, i):
            return error('Error updating instance')

    instance.save()
    if not instance:
        return error("Error saving object")

    updated_instance_dict = dict_from_single_object(instance, allowed_fields)
    if not updated_instance_dict:
        return error("Error generating response")

    updated_instance_dict["success"] = True
    print(updated_instance_dict)
    return JsonResponse(updated_instance_dict, safe=False)