예제 #1
0
    def _send(self, request):
        response = self.client.http.send(request)

        if response is None:
            if self.exceptions:
                raise RequestFailedError('No response available')

            log.warning('Request failed (no response returned)')
            return None

        if response.status_code < 200 or response.status_code >= 300:
            log_request_error(log, response)

            # Raise an exception (if enabled)
            if self.exceptions:
                if response.status_code >= 500:
                    raise ServerError(response)
                else:
                    raise ClientError(response)

            return None

        # Update pagination state
        self.per_page = try_convert(response.headers.get('x-pagination-limit'), int)
        self.total_items = try_convert(response.headers.get('x-pagination-item-count'), int)
        self.total_pages = try_convert(response.headers.get('x-pagination-page-count'), int)

        return response
예제 #2
0
파일: mock.py 프로젝트: pjpalomaki/trakt.py
def lists(url, request, content_type='application/json'):
    parameters = dict(parse_qsl(url.query))

    page = try_convert(parameters.get('page'), int) or 1
    limit = try_convert(parameters.get('limit'), int) or 10

    # Retrieve items from fixture
    items = get_json(url.netloc, url.path, url.query)

    if items is None:
        return httmock.response(404, request=request)

    # Calculate page count and item offset
    offset = (page - 1) * limit
    page_count = int(math.ceil(float(len(items)) / limit))

    return httmock.response(
        200, json.dumps(items[offset:offset + limit]), {
            'Content-Type': content_type,

            'X-Pagination-Page': page,
            'X-Pagination-Limit': limit,
            'X-Pagination-Page-Count': page_count,
            'X-Pagination-Item-Count': len(items)
        },
        request=request
    )
예제 #3
0
파일: mock.py 프로젝트: fuzeman/trakt.py
def lists(url, request, content_type='application/json'):
    parameters = dict(parse_qsl(url.query))

    page = try_convert(parameters.get('page'), int) or 1
    limit = try_convert(parameters.get('limit'), int) or 10

    # Retrieve items from fixture
    items = get_json(url.netloc, url.path, url.query)

    if items is None:
        return httmock.response(404, request=request)

    # Calculate page count and item offset
    offset = (page - 1) * limit
    page_count = int(math.ceil(float(len(items)) / limit))

    return httmock.response(
        200, json.dumps(items[offset:offset + limit]), {
            'Content-Type': content_type,

            'X-Pagination-Page': page,
            'X-Pagination-Limit': limit,
            'X-Pagination-Page-Count': page_count,
            'X-Pagination-Item-Count': len(items)
        },
        request=request
    )
예제 #4
0
    def __init__(self, client, response):
        self.client = client
        self.response = response

        # Retrieve pagination headers
        self.per_page = try_convert(response.headers.get('x-pagination-limit'), int)
        self.total_items = try_convert(response.headers.get('x-pagination-item-count'), int)
        self.total_pages = try_convert(response.headers.get('x-pagination-page-count'), int)
예제 #5
0
    def __init__(self, client, response):
        self.client = client
        self.response = response

        # Retrieve pagination headers
        self.per_page = try_convert(response.headers.get('x-pagination-limit'),
                                    int)
        self.total_items = try_convert(
            response.headers.get('x-pagination-item-count'), int)
        self.total_pages = try_convert(
            response.headers.get('x-pagination-page-count'), int)
예제 #6
0
    def __init__(self, client, response):
        self.client = client
        self.response = response

        # Retrieve pagination headers
        self.per_page = try_convert(response.headers.get('x-pagination-limit'), int)
        self.total_items = try_convert(response.headers.get('x-pagination-item-count'), int)
        self.total_pages = try_convert(response.headers.get('x-pagination-page-count'), int)

        # Parse request url
        scheme, netloc, path, query = urlsplit(self.response.request.url)[:4]

        self.url = urlunsplit([scheme, netloc, path, '', ''])
        self.query = dict(parse_qsl(query))
예제 #7
0
    def __init__(self, client, response):
        self.client = client
        self.response = response

        # Retrieve pagination headers
        self.per_page = try_convert(response.headers.get('x-pagination-limit'), int)
        self.total_items = try_convert(response.headers.get('x-pagination-item-count'), int)
        self.total_pages = try_convert(response.headers.get('x-pagination-page-count'), int)

        # Parse request url
        scheme, netloc, path, query = urlsplit(self.response.request.url)[:4]

        self.url = urlunsplit([scheme, netloc, path, '', ''])
        self.query = dict(parse_qsl(query))
예제 #8
0
    def on_request(request):
        url = urlparse(request.url)
        parameters = dict(parse_qsl(url.query))

        page = try_convert(parameters.get('page'), int) or 1
        limit = try_convert(parameters.get('limit'), int)

        if limit is not None and limit != 2:
            # Invalid limit provided
            return 400, {}, ''

        return 200, {
            'X-Pagination-Limit': '2',
            'X-Pagination-Item-Count': '6',
            'X-Pagination-Page-Count': '3'
        }, read('fixtures/users/me/lists_p%d.json' % page)
예제 #9
0
    def on_request(request):
        url = urlparse(request.url)
        parameters = dict(parse_qsl(url.query))

        page = try_convert(parameters.get('page'), int) or 1
        limit = try_convert(parameters.get('limit'), int)

        if limit is not None and limit != 2:
            # Invalid limit provided
            return 400, {}, ''

        return 200, {
            'X-Pagination-Limit':       '2',
            'X-Pagination-Item-Count':  '6',
            'X-Pagination-Page-Count':  '3'
        }, read('fixtures/users/me/lists_p%d.json' % page)
예제 #10
0
    def get_data(self, response, exceptions=False, pagination=False, parse=True):
        if response is None:
            return None

        # Return response, if parse=False
        if not parse:
            return response

        # Check status code, log any errors
        error = False

        if response.status_code < 200 or response.status_code >= 300:
            # Lookup status code in trakt error definitions
            name, desc = ERRORS.get(response.status_code, ("Unknown", "Unknown"))

            log.warning('Request failed: %s - "%s" (code: %s)', name, desc, response.status_code)

            if exceptions:
                # Raise an exception (including the response for further processing)
                if response.status_code >= 500:
                    raise ServerError(response)
                else:
                    raise ClientError(response)

            # Set error flag
            error = True

        # Return `None` if we encountered an error, return response data
        if error:
            return None

        # Check for pagination response
        page_count = try_convert(response.headers.get('x-pagination-page-count'), int)

        if page_count and page_count > 1:
            if pagination:
                return PaginationIterator(self.client, response)

            warnings.warn('Unhandled pagination response, more pages can be returned with `pagination=True`', stacklevel=3)

        # Parse response, return data
        content_type = response.headers.get('content-type')

        if content_type and content_type.startswith('application/json'):
            # Try parse json response
            try:
                data = response.json()
            except Exception as e:
                log.warning('unable to parse JSON response: %s', e)
                return None
        else:
            log.debug('response returned content-type: %r, falling back to raw data', content_type)

            # Fallback to raw content
            data = response.content

        return data
예제 #11
0
파일: mock.py 프로젝트: pjpalomaki/trakt.py
def lists_request_failure(url, request):
    parameters = dict(parse_qsl(url.query))

    page = try_convert(parameters.get('page'), int) or 1

    # Return invalid response for page #2
    if page == 2:
        return httmock.response(400, request=request)

    # Return page
    return lists(url, request)
예제 #12
0
파일: mock.py 프로젝트: fuzeman/trakt.py
def lists_request_failure(url, request):
    parameters = dict(parse_qsl(url.query))

    page = try_convert(parameters.get('page'), int) or 1

    # Return invalid response for page #2
    if page == 2:
        return httmock.response(400, request=request)

    # Return page
    return lists(url, request)
예제 #13
0
파일: mock.py 프로젝트: ruinernin/trakt.py
def lists_invalid_json(url, request):
    parameters = dict(parse_qsl(url.query))

    page = try_convert(parameters.get('page'), int) or 1

    # Return invalid response for page #2
    if page == 2:
        return httmock.response(200,
                                '<invalid-json-response>',
                                {'Content-Type': 'application/json'},
                                request=request)

    # Return page
    return lists(url, request)
예제 #14
0
파일: mock.py 프로젝트: fuzeman/trakt.py
def lists_invalid_json(url, request):
    parameters = dict(parse_qsl(url.query))

    page = try_convert(parameters.get('page'), int) or 1

    # Return invalid response for page #2
    if page == 2:
        return httmock.response(
            200, '<invalid-json-response>', {
                'Content-Type': 'application/json'
            },
            request=request
        )

    # Return page
    return lists(url, request)
예제 #15
0
    def get_data(self, response, exceptions=False, pagination=False, parse=True):
        if response is None:
            if exceptions:
                raise RequestFailedError('No response available')

            log.warn('Request failed (no response returned)')
            return None

        # Return response, if parse=False
        if not parse:
            return response

        # Check status code, log any errors
        error = False

        if response.status_code < 200 or response.status_code >= 300:
            log_request_error(log, response)

            # Raise an exception (if enabled)
            if exceptions:
                if response.status_code >= 500:
                    raise ServerError(response)
                else:
                    raise ClientError(response)

            # Set error flag
            error = True

        # Return `None` if we encountered an error, return response data
        if error:
            return None

        # Check for pagination response
        page_count = try_convert(response.headers.get('x-pagination-page-count'), int)

        if page_count and page_count > 1:
            if pagination:
                return PaginationIterator(self.client, response)

            warnings.warn(
                'Unhandled pagination response, more pages can be returned with `pagination=True`',
                stacklevel=3
            )

        # Parse response, return data
        content_type = response.headers.get('content-type')

        if content_type and content_type.startswith('application/json'):
            # Try parse json response
            try:
                data = response.json()
            except Exception as e:
                log.warning('unable to parse JSON response: %s', e)
                return None
        else:
            log.debug('response returned content-type: %r, falling back to raw data', content_type)

            # Fallback to raw content
            data = response.content

        return data
예제 #16
0
    def get_data(self,
                 response,
                 exceptions=False,
                 pagination=False,
                 parse=True):
        if response is None:
            return None

        # Return response, if parse=False
        if not parse:
            return response

        # Check status code, log any errors
        error = False

        if response.status_code < 200 or response.status_code >= 300:
            # Lookup status code in trakt error definitions
            name, desc = ERRORS.get(response.status_code,
                                    ("Unknown", "Unknown"))

            log.warning('Request failed: %s - "%s" (code: %s)', name, desc,
                        response.status_code)

            if exceptions:
                # Raise an exception (including the response for further processing)
                if response.status_code >= 500:
                    raise ServerError(response)
                else:
                    raise ClientError(response)

            # Set error flag
            error = True

        # Return `None` if we encountered an error, return response data
        if error:
            return None

        # Check for pagination response
        page_count = try_convert(
            response.headers.get('x-pagination-page-count'), int)

        if page_count and page_count > 1:
            if pagination:
                return PaginationIterator(self.client, response)

            warnings.warn(
                'Unhandled pagination response, more pages can be returned with `pagination=True`',
                stacklevel=3)

        # Parse response, return data
        content_type = response.headers.get('content-type')

        if content_type and content_type.startswith('application/json'):
            # Try parse json response
            try:
                data = response.json()
            except Exception as e:
                log.warning('unable to parse JSON response: %s', e)
                return None
        else:
            log.debug(
                'response returned content-type: %r, falling back to raw data',
                content_type)

            # Fallback to raw content
            data = response.content

        return data