コード例 #1
0
ファイル: client.py プロジェクト: apsharkey/parselmouth
    def _format_query(self,
                      order=DFP_QUERY_DEFAULTS['order'],
                      limit=None,
                      offset=DFP_QUERY_DEFAULTS['offset'],
                      **filter_kwargs):
        """
        Query formatter

        @param query_dict: dictionary of query parameters to organize
            into a PQL statemente
        @param order: str, PQL key to sort on (default=ID)
        @param limit: int, number of PQL results to return
        @param offset: int, page in a stream of PQL results to return
        @param filter_kwargs: dict, keyword arguments on which to filter
            PQL results
        @return: FilterStatement, PQL statement

        ## TODO: We probably want to do some checking of `filter_kwargs`
            against available column names in DFP PQL tables
        """
        if order:
            query = "ORDER BY {order}".format(order=order)
        else:
            query = ""

        filters = []
        for key, val in filter_kwargs.iteritems():
            if isinstance(val, list):
                # gotta format that in query
                _dfp_list = ", ".join([str(x) for x in val])
                filters.append("{0} IN ({1})".format(key, _dfp_list))
                pass
            else:
                filters.append("{0}={1}".format(key, val))
        if filters:
            # Prepend the where parameters to the base query
            where_query = " AND ".join(filters)

            query = "WHERE {where} {order}".format(
                where=where_query,
                order=query,
            )

        statement = FilterStatement(query)
        if limit:
            statement.limit = limit
        if offset:
            statement.offset = offset

        return statement
コード例 #2
0
    def _format_query(self,
                      order=DFP_QUERY_DEFAULTS['order'],
                      limit=None,
                      offset=DFP_QUERY_DEFAULTS['offset'],
                      **filter_kwargs):
        """
        Query formatter

        @param query_dict: dictionary of query parameters to organize
            into a PQL statemente
        @param order: str, PQL key to sort on (default=ID)
        @param limit: int, number of PQL results to return
        @param offset: int, page in a stream of PQL results to return
        @param filter_kwargs: dict, keyword arguments on which to filter
            PQL results
        @return: FilterStatement, PQL statement

        ## TODO: We probably want to do some checking of `filter_kwargs`
            against available column names in DFP PQL tables
        """
        if order:
            query = "ORDER BY {order}".format(order=order)
        else:
            query = ""

        filters = []
        for key, val in filter_kwargs.iteritems():
            if isinstance(val, list):
                # gotta format that in query
                _dfp_list = ", ".join([str(x) for x in val])
                filters.append("{0} IN ({1})".format(key, _dfp_list))
                pass
            else:
                filters.append("{0}={1}".format(key, val))
        if filters:
            # Prepend the where parameters to the base query
            where_query = " AND ".join(filters)

            query = "WHERE {where} {order}".format(
                where=where_query,
                order=query,
            )

        statement = FilterStatement(query)
        if limit:
            statement.limit = limit
        if offset:
            statement.offset = offset

        return statement
コード例 #3
0
    def get_line_item_creatives(self, line_item_id):
        """
        Get the creatives assoicated with a particular line item

        @param line_item_id: int, the line item id
        @return: list(str), list of creative ids associated with the
            given line item
        """
        values = [{
            'key': 'lineItemId',
            'value': {
                'xsi_type': 'NumberValue',
                'value': line_item_id
            }
        }]
        query = 'WHERE lineItemId = :lineItemId'
        statement = FilterStatement(where_clause=query, values=values)
        service = self.native_dfp_client.GetService(
            'LineItemCreativeAssociationService', version=self.version)

        creatives = self._run_service_query(
            statement,
            service.getLineItemCreativeAssociationsByStatement,
        )

        if creatives:
            if 'results' in creatives:
                return [
                    str(creative['creativeId'])
                    for creative in creatives['results']
                ]
            else:
                return [str(creative['creativeId']) for creative in creatives]
        else:
            return []
コード例 #4
0
    def get_advertisers(self):
        """
        Queries dfp for all advertisers within their account

        @return: list(dict), returns a list of company dictionaries
        """
        service = self.native_dfp_client.GetService(
            'CompanyService',
            version=self.version,
        )

        # Create statement object to only select companies that are advertisers
        values = [{
            'key': 'type',
            'value': {
                'xsi_type': 'TextValue',
                'value': 'ADVERTISER'
            }
        }]
        query = 'WHERE type = :type'
        statement = FilterStatement(query, values)
        results = self._run_service_query(statement,
                                          service.getCompaniesByStatement)
        advertisers = [{
            'id': advertiser['id'],
            'name': advertiser['name']
        } for advertiser in results]
        return advertisers
コード例 #5
0
    def _GetLimitedResults(self,
                           getter_func,
                           network_code=None,
                           statement=None,
                           is_pql_result=False):
        """Returns up to 25 entities given a getter_func.

    The set of users returned can be altered by specifying a statement with
    an offset or a limit less than 25.

    Args:
      getter_func: func Function to retrieve results from a service.
      network_code: str Network code to use when interacting with the service.
                    Defaults to None.
      statement: FilterStatement PQL Statement to filter results.
                 Defaults to None.
      is_pql_result: The response from the DFP API is coming from the
                     PQL Service and will only include the results.
                     Defaults to False.

    Returns:
      dict Dict including a list of data objects and total set size.
    """
        self.client.network_code = network_code
        if statement:
            statement.limit = min(statement.limit, self.page_limit)
        else:
            statement = FilterStatement(limit=self.page_limit)
        response = getter_func(statement.ToStatement())
        if is_pql_result:
            return {
                'results':
                response['rows'] if 'rows' in response else [],
                'columns':
                [column['labelName'] for column in response['columnTypes']],
            }

        total_result_set_size = response['totalResultSetSize']
        results = response['results'] if total_result_set_size > 0 else []
        return {
            'results': results,
            'totalResultSetSize': total_result_set_size,
        }
コード例 #6
0
    def get_custom_targets(self, key_name=None, value_name=None):
        """
        Get all custom targeting key and value data

        @param key_name: str|None, if present only return
            targeting with the given key name
        @param value_name: str|None, if present only return
            targeting with the given value name
        @return: list(dict)
        """
        service = self.native_dfp_client.GetService(
            'CustomTargetingService',
            version=self.version,
        )

        if key_name:
            values = [{
                'key': 'name',
                'value': {
                    'xsi_type': 'TextValue',
                    'value': key_name,
                }
            }]
            query = 'WHERE name = :name'
            key_statement = FilterStatement(query, values)
        else:
            key_statement = FilterStatement()

        key_results = self._run_service_query(
            key_statement,
            service.getCustomTargetingKeysByStatement,
        )

        custom_data = []
        if not key_results:
            return custom_data

        if not value_name:
            # In the case when value_name is given, do not include
            # the key target
            custom_data += key_results

        # Create statement to get all targeting values.
        query = 'WHERE customTargetingKeyId IN ({})'.format(
            ', '.join([str(key['id']) for key in key_results]), )

        if value_name:
            values = [{
                'key': 'name',
                'value': {
                    'xsi_type': 'TextValue',
                    'value': value_name,
                }
            }]
            query += ' AND name = :name'
            value_statement = FilterStatement(query, values)
        else:
            value_statement = FilterStatement(query)

        # Get custom targeting values by statement.
        value_results = self._run_service_query(
            value_statement,
            service.getCustomTargetingValuesByStatement,
        )
        custom_data += value_results
        return custom_data