Add pagination headers to the bottle response.

    See docs in :func:`paginated`.

def write_pagination_headers(data, offset, limit, response, uripath,
                             resource_name):
    """Add pagination headers to the bottle response.

    See docs in :func:`paginated`.
    """
    items = data.get('results') or data.get('data') or {}
    count = len(items)
    try:
        total = int(data['collection-count'])
    except (ValueError, TypeError, KeyError):
        total = None
    if total is None and offset == 0 and (limit is None or limit > len(items)):
        total = count

    # Set 'content-range' header
    response.set_header(
        'Content-Range',
        "%s %d-%d/%s" % (resource_name, offset, offset + max(count - 1, 0),
                         total if total is not None else '*')
    )

    partial = False
    if offset:
        partial = True  # Any offset automatically means we've skipped data
    elif total is None and count == limit:
        # Unknown total, but first page is full (so there may be more)
        partial = True  # maybe more records in next page
    elif total > count:
        # Known total and not all records returned
        partial = True

    if partial:
        uripath = uripath.strip('/')
        response.status = 206  # Partial

        # Add Next page link to http header
        if total is None or (offset + limit) < total - 1:
            nextfmt = (
                '</%s?limit=%d&offset=%d>; rel="next"; title="Next page"')
            response.add_header(
                "Link", nextfmt % (uripath, limit, offset + limit)
            )

        # Add Previous page link to http header
        if offset > 0 and (offset - limit) >= 0:
            prevfmt = ('</%s?limit=%d&offset=%d>; rel="previous"; '
                       'title="Previous page"')
            response.add_header(
                "Link", prevfmt % (uripath, limit, offset - limit)
            )

        # Add first page link to http header
        if offset > 0:
            firstfmt = '</%s?limit=%d>; rel="first"; title="First page"'
            response.add_header(
                "Link", firstfmt % (uripath, limit))

        # Add last page link to http header
        if (total is not None and  # can't calculate last page if unknown total
                limit and  # if no limit, then any page is the last page!
                limit < total):
            lastfmt = '</%s?offset=%d>; rel="last"; title="Last page"'
            if limit and total % limit:
                last_offset = total - (total % limit)
            else:
                last_offset = total - limit
            response.add_header(
                "Link", lastfmt % (uripath, last_offset))