예제 #1
0
파일: record.py 프로젝트: greeshmab/syncto
def record_put(request):
    collection_name = request.matchdict['collection_name']

    assert_endpoint_enabled(request, collection_name)

    record_id = request.matchdict['record_id']
    sync_id = record_id

    headers = import_headers(request)
    record = request.validated['data']
    record['id'] = sync_id

    # Remove read-only fields
    record.pop('last_modified', None)

    sync_client = build_sync_client(request)
    last_modified = sync_client.put_record(collection_name, record,
                                           headers=headers)
    record['last_modified'] = int(last_modified * 1000)
    record['id'] = record_id

    # Configure headers
    export_headers(sync_client.raw_resp, request)

    status_code(request,str="syncclient.status_code.200")

    return {'data': record}
def record_put(request):
    collection_name = request.matchdict['collection_name']

    assert_endpoint_enabled(request, collection_name)

    record_id = request.matchdict['record_id']
    sync_id = record_id

    headers = import_headers(request)
    record = request.validated['data']
    record['id'] = sync_id

    # Remove read-only fields
    record.pop('last_modified', None)

    sync_client = build_sync_client(request)
    last_modified = sync_client.put_record(collection_name,
                                           record,
                                           headers=headers)
    record['last_modified'] = int(last_modified * 1000)
    record['id'] = record_id

    # Configure headers
    export_headers(sync_client.raw_resp, request)

    statsd_count(request, "syncclient.status_code.200")

    return {'data': record}
예제 #3
0
def collection_get(request):
    collection_name = request.matchdict['collection_name']
    sync_client = build_sync_client(request)

    headers = import_headers(request)

    params = {}
    if '_since' in request.GET:
        try:
            params['newer'] = '%.2f' % (int(request.GET['_since']) / 1000.0)
        except ValueError:
            error_msg = ("_since should be a number.")
            raise_invalid(request,
                          location="querystring",
                          name="_since",
                          description=error_msg)

    if '_limit' in request.GET:
        params['limit'] = request.GET['_limit']

    if '_token' in request.GET:
        params['offset'] = request.GET['_token']

    if '_sort' in request.GET:
        if request.GET['_sort'] in ('-last_modified', 'newest'):
            params['sort'] = 'newest'

        elif request.GET['_sort'] in ('-sortindex', 'index'):
            params['sort'] = 'index'

        elif request.GET['_sort'] in ('last_modified', 'oldest'):
            params['sort'] = 'oldest'

        else:
            error_msg = ("_sort should be one of ('-last_modified', 'newest', "
                         "'-sortindex', 'index', 'last_modified', 'oldest')")
            raise_invalid(request,
                          location="querystring",
                          name="_sort",
                          description=error_msg)

    if 'in_ids' in request.GET:
        params['ids'] = [record_id.strip() for record_id in
                         request.GET['in_ids'].split(',') if record_id]

    records = sync_client.get_records(collection_name, full=True,
                                      headers=headers, **params)

    statsd_count(request, "syncclient.status_code.200")

    for r in records:
        r['last_modified'] = int(r.pop('modified') * 1000)

    # Configure headers
    export_headers(sync_client.raw_resp, request)

    if '_limit' in request.GET and 'Total-Records' in request.response.headers:
        del request.response.headers['Total-Records']

    return {'data': records or []}
예제 #4
0
def collection_get(request):
    collection_name = request.matchdict["collection_name"]
    sync_client = build_sync_client(request)

    headers = import_headers(request)

    params = {}
    if "_since" in request.GET:
        try:
            params["newer"] = "%.2f" % (int(request.GET["_since"]) / 1000.0)
        except ValueError:
            error_msg = "_since should be a number."
            raise_invalid(request, location="querystring", name="_since", description=error_msg)

    if "_limit" in request.GET:
        params["limit"] = request.GET["_limit"]

    if "_token" in request.GET:
        params["offset"] = request.GET["_token"]

    if "_sort" in request.GET:
        if request.GET["_sort"] in ("-last_modified", "newest"):
            params["sort"] = "newest"

        elif request.GET["_sort"] in ("-sortindex", "index"):
            params["sort"] = "index"

        elif request.GET["_sort"] in ("last_modified", "oldest"):
            params["sort"] = "oldest"

        else:
            error_msg = (
                "_sort should be one of ('-last_modified', 'newest', "
                "'-sortindex', 'index', 'last_modified', 'oldest')"
            )
            raise_invalid(request, location="querystring", name="_sort", description=error_msg)

    if "in_ids" in request.GET:
        params["ids"] = [record_id.strip() for record_id in request.GET["in_ids"].split(",") if record_id]

    records = sync_client.get_records(collection_name, full=True, headers=headers, **params)

    status_code(request, str="syncclient.status_code.200")

    for r in records:
        r["last_modified"] = int(r.pop("modified") * 1000)

    # Configure headers
    export_headers(sync_client.raw_resp, request)

    if "_limit" in request.GET and "Total-Records" in request.response.headers:
        del request.response.headers["Total-Records"]

    if records:
        return {"data": records}
def response_error(context, request):
    """Catch response error from Sync and trace them."""
    message = '%s %s: %s' % (context.response.status_code,
                             context.response.reason,
                             context.response.text)

    # XXX: Make sure these HTTPError exception are coming from SyncClient.
    statsd_count(request, "syncclient.status_code.%s" %
                 context.response.status_code)

    if context.response.status_code in (400, 401, 403, 404):
        # For this code we also want to log the info about the error.
        logger.info(context, exc_info=True)

    # For this specific code we do not want to log the error.
    if context.response.status_code == 304:
        response = httpexceptions.HTTPNotModified()
    elif context.response.status_code == 400:
        response = http_error(httpexceptions.HTTPBadRequest(),
                              errno=ERRORS.INVALID_PARAMETERS,
                              message=message)
    elif context.response.status_code == 401:
        response = http_error(httpexceptions.HTTPUnauthorized(),
                              errno=ERRORS.INVALID_AUTH_TOKEN,
                              message=message)
        # Forget the current user credentials.
        response.headers.extend(forget(request))
    elif context.response.status_code == 403:
        response = http_error(httpexceptions.HTTPForbidden(),
                              errno=ERRORS.FORBIDDEN,
                              message=message)
    elif context.response.status_code == 404:
        response = http_error(httpexceptions.HTTPNotFound(),
                              errno=ERRORS.INVALID_RESOURCE_ID,
                              message=message)
    elif context.response.status_code == 412:
        message = 'Resource was modified meanwhile'
        response = http_error(httpexceptions.HTTPPreconditionFailed(),
                              errno=ERRORS.MODIFIED_MEANWHILE,
                              message=message)
    else:
        # For this code we also want to log the error.
        logger.error(context, exc_info=True)
        response = service_unavailable(
            httpexceptions.HTTPServiceUnavailable(),
            request)

    request.response = response
    export_headers(context.response, request)

    return reapply_cors(request, response)
예제 #6
0
파일: record.py 프로젝트: greeshmab/syncto
def record_get(request):
    collection_name = request.matchdict['collection_name']
    record_id = request.matchdict['record_id']

    sync_client = build_sync_client(request)
    headers = import_headers(request)
    record = sync_client.get_record(collection_name, record_id,
                                    headers=headers)

    record['last_modified'] = int(record.pop('modified') * 1000)

    # Configure headers
    export_headers(sync_client.raw_resp, request)

    status_code(request,str="syncclient.status_code.200")

    return {'data': record}
def record_get(request):
    collection_name = request.matchdict['collection_name']
    record_id = request.matchdict['record_id']

    sync_client = build_sync_client(request)
    headers = import_headers(request)
    record = sync_client.get_record(collection_name,
                                    record_id,
                                    headers=headers)

    record['last_modified'] = int(record.pop('modified') * 1000)

    # Configure headers
    export_headers(sync_client.raw_resp, request)

    statsd_count(request, "syncclient.status_code.200")

    return {'data': record}
예제 #8
0
def collection_get(request):
    collection_name = request.matchdict['collection_name']
    sync_client = build_sync_client(request)

    headers = import_headers(request)

    params = {}
    if '_since' in request.GET:
        try:
            params['newer'] = '%.2f' % (int(request.GET['_since']) / 1000.0)
        except ValueError:
            error_msg = ("_since should be a number.")
            raise_invalid(request,
                          location="querystring",
                          name="_since",
                          description=error_msg)

    if '_limit' in request.GET:
        params['limit'] = request.GET['_limit']

    if '_token' in request.GET:
        params['offset'] = request.GET['_token']

    if '_sort' in request.GET:
        if request.GET['_sort'] in ('-last_modified', 'newest'):
            params['sort'] = 'newest'

        elif request.GET['_sort'] in ('-sortindex', 'index'):
            params['sort'] = 'index'

        elif request.GET['_sort'] in ('last_modified', 'oldest'):
            params['sort'] = 'oldest'

        else:
            error_msg = ("_sort should be one of ('-last_modified', 'newest', "
                         "'-sortindex', 'index', 'last_modified', 'oldest')")
            raise_invalid(request,
                          location="querystring",
                          name="_sort",
                          description=error_msg)

    if 'in_ids' in request.GET:
        params['ids'] = [
            record_id.strip() for record_id in request.GET['in_ids'].split(',')
            if record_id
        ]

    records = sync_client.get_records(collection_name,
                                      full=True,
                                      headers=headers,
                                      **params)

    statsd_count(request, "syncclient.status_code.200")

    for r in records:
        r['last_modified'] = int(r.pop('modified') * 1000)

    # Configure headers
    export_headers(sync_client.raw_resp, request)

    if '_limit' in request.GET and 'Total-Records' in request.response.headers:
        del request.response.headers['Total-Records']

    return {'data': records or []}