Exemple #1
0
 def __init__(self):
     auth = dict(settings.DFP_HEADERS)
     auth['oauth2credentials'] = OAuth2Credentials(
         None, auth['clientId'], auth['clientSecret'], auth['refreshToken'],
         datetime.datetime(1980, 1, 1, 12), _GOOGLE_OAUTH2_ENDPOINT,
         'Google Ads* Python Client Library')
     self.client = DfpClient(headers=auth, config=settings.DFP_CONFIG)
    def testInitDfpClientWithClientLoginNotSupported(self):
        """Ensures the DFP library throws an error for clientLogin on > v201311."""

        headers = {
            'authToken': 'THIS IS A NO NO AFTER v201311!',
            'applicationName': 'APPLICATION NAME MUST NOT BE EMPTY'
        }
        client = DfpClient(headers=headers)
        with mock.patch('adspygoogle.SOAPpy.WSDL.Proxy'):
            network_service_fine = client.GetNetworkService(version='v201311')
            self.assertRaises(ApiVersionNotSupportedError,
                              client.GetNetworkService,
                              version='v201403')
Exemple #3
0
class DoubleClickNetwork(BaseNetwork):
    VERSION = 'v201306'
    AD_UNIT_PREFIX = 'TheCrimson'
    MOBILE_KEY = 'Mobile'
    DESKTOP_KEY = 'Desktop'

    def __init__(self):
        auth = dict(settings.DFP_HEADERS)
        auth['oauth2credentials'] = OAuth2Credentials(
            None, auth['clientId'], auth['clientSecret'], auth['refreshToken'],
            datetime.datetime(1980, 1, 1, 12), _GOOGLE_OAUTH2_ENDPOINT,
            'Google Ads* Python Client Library')
        self.client = DfpClient(headers=auth, config=settings.DFP_CONFIG)

    def get_root_node_id(self):
        network_service = self.client.GetNetworkService(version=self.VERSION)
        network = network_service.GetCurrentNetwork()[0]
        return network['effectiveRootAdUnitId']

    def _update_ad_units(self):
        inventory = self.client.GetInventoryService(version=self.VERSION)
        values = [{
            'key': 'parentId',
            'value': {
                'xsi_type': 'TextValue',
                'value': self.get_root_node_id()
            }
        }]
        filter_statement = {
            'query': "WHERE status = 'ACTIVE' AND parentId = :parentId",
            'values': values
        }
        ad_units = inventory.GetAdUnitsByStatement(filter_statement)[0]
        ad_units = ad_units.get('results', [])
        for ad_unit in ad_units:
            if not ad_unit['adUnitCode'].startswith(self.AD_UNIT_PREFIX):
                continue

            AdUnit.objects.create_or_update(
                code=ad_unit['adUnitCode'],
                network_id=ad_unit['id'],
                size=ad_unit['adUnitSizes'][0]['fullDisplayString'],
                display_on=AdUnit.MOBILE_AND_DESKTOP)
  def testIssue57(self):
    """Tests thats Issue 57 has been correctly fixed.

    Since this library is tightly integrated with SOAPpy, this test mocks out
    the HTTP level rather than the SOAPpy proxy level.
    """
    client = DfpClient(headers={
        'applicationName': APPLICATION_NAME,
        'networkId': NETWORK_CODE,
        'oauth2credentials': OAuth2Credentials(
            ACCESS_TOKEN, 'client_id', 'client_secret', 'refresh_token', None,
            'uri', 'user_agent')
    })

    line_item_service = self._CreateLineItemService(client)
    line_item_service._config['compress'] = False

    self._MakeSoapRequest(line_item_service)
Exemple #5
0
website. To download the report run download_report.py."""

__author__ = '[email protected] (Stan Grinberg)'

# Locate the client library. If module was installed via "setup.py" script, then
# the following two lines are not needed.
import os
import sys
sys.path.append(os.path.join('..', '..', '..', '..'))
import time

# Import appropriate classes from the client library.
from adspygoogle.dfp.DfpClient import DfpClient

# Initialize client object.
client = DfpClient(path=os.path.join('..', '..', '..', '..'))

# Initialize appropriate service. By default, the request is always made against
# sandbox environment.
report_service = client.GetReportService('https://sandbox.google.com',
                                         'v201004')

# Create report job.
report_job = {
    'reportQuery': {
        'dimensions': ['ORDER'],
        'columns': [
            'AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS', 'AD_SERVER_CTR',
            'AD_SERVER_REVENUE', 'AD_SERVER_AVERAGE_ECPM'
        ],
        'dateRangeType':
get_all_custom_targeting_keys_and_values.py. To target these custom targeting
keys and values, run target_custom_criteria_example.py."""

__author__ = '[email protected] (Stan Grinberg)'

# Locate the client library. If module was installed via "setup.py" script, then
# the following two lines are not needed.
import os
import sys
sys.path.append(os.path.join('..', '..', '..', '..'))

# Import appropriate classes from the client library.
from adspygoogle.dfp.DfpClient import DfpClient

# Initialize client object.
client = DfpClient(path=os.path.join('..', '..', '..', '..'))

# Initialize appropriate service. By default, the request is always made against
# sandbox environment.
custom_targeting_service = client.GetCustomTargetingService(
    'https://sandbox.google.com', 'v201101')

# Create custom targeting key objects.
keys = [{
    'displayName': 'gender',
    'name': 'g',
    'type': 'PREDEFINED'
}, {
    'displayName': 'car model',
    'name': 'c',
    'type': 'FREEFORM'
Exemple #7
0
exist, run get_ad_unit_tree.py or get_all_ad_units.py."""

__author__ = '[email protected] (Stan Grinberg)'

# Locate the client library. If module was installed via "setup.py" script, then
# the following two lines are not needed.
import os
import sys

sys.path.append(os.path.join('..', '..', '..', '..'))

# Import appropriate classes from the client library.
from adspygoogle.dfp.DfpClient import DfpClient

# Initialize client object.
client = DfpClient(path=os.path.join('..', '..', '..', '..'))

# Initialize appropriate service. By default, the request is always made against
# sandbox environment.
inventory_service = client.GetInventoryService('https://sandbox.google.com',
                                               'v201004')

# Set the id of the ad unit to get.
ad_unit_id = 'INSERT_AD_UNIT_ID_HERE'

# Get ad unit.
ad_unit = inventory_service.GetAdUnit(ad_unit_id)[0]

# Display results.
print('Ad unit with id \'%s\', name \'%s\', and status \'%s\' was created.' %
      (ad_unit['id'], ad_unit['name'], ad_unit['status']))
"""This code example gets a forecast for an existing line item. To determine
which ine items exist, run get_all_line_items.py."""

__author__ = '[email protected] (Stan Grinberg)'

# Locate the client library. If module was installed via "setup.py" script, then
# the following two lines are not needed.
import os
import sys
sys.path.append(os.path.join('..', '..', '..', '..'))

# Import appropriate classes from the client library.
from adspygoogle.dfp.DfpClient import DfpClient

# Initialize client object.
client = DfpClient(path=os.path.join('..', '..', '..', '..'))

# Initialize appropriate service. By default, the request is always made against
# the sandbox environment.
forecast_service = client.GetForecastService('https://sandbox.google.com',
                                             'v201010')

# Set the line item to get a forecast for.
line_item_id = 'INSERT_LINE_ITEM_ID'

# Get forecast for line item.
forecast = forecast_service.GetForecastById(line_item_id)[0]
matched = long(forecast['matchedUnits'])
available_percent = (long(forecast['availableUnits']) / (matched * 1.0)) * 100

# Display results.
run get_all_placements.py."""

__author__ = '[email protected] (Stan Grinberg)'

# Locate the client library. If module was installed via "setup.py" script, then
# the following two lines are not needed.
import os
import sys
sys.path.append(os.path.join('..', '..', '..', '..'))

# Import appropriate classes from the client library.
from adspygoogle.dfp.DfpClient import DfpClient


# Initialize client object.
client = DfpClient(path=os.path.join('..', '..', '..', '..'))
client.strict = False

# Initialize appropriate service. By default, the request is always made against
# the sandbox environment.
forecast_service = client.GetForecastService(
    'https://sandbox.google.com', 'v201010')

# Set the placement that the prospective line item will target.
target_placement_ids = ['INSERT_PLACEMENT_ID_HERE']

# Create prospective line item.
line_item = {
    'targeting': {
        'inventoryTargeting': {
            'targetedPlacementIds': target_placement_ids
Exemple #10
0
run get_all_placements.py."""

__author__ = '[email protected] (Stan Grinberg)'

# Locate the client library. If module was installed via "setup.py" script, then
# the following two lines are not needed.
import os
import sys
sys.path.append(os.path.join('..', '..', '..', '..'))

# Import appropriate classes from the client library.
from adspygoogle.dfp.DfpClient import DfpClient


# Initialize client object.
client = DfpClient(path=os.path.join('..', '..', '..', '..'))
client.strict = False

# Initialize appropriate service. By default, the request is always made against
# the sandbox environment.
forecast_service = client.GetForecastService(
    'https://sandbox.google.com', 'v201004')

# Set the placement that the prospective line item will target.
target_placement_ids = ['INSERT_PLACEMENT_ID_HERE']

# Create hypothetical line item.
line_item = {
    'targeting': {
        'inventoryTargeting': {
            'targetedPlacementIds': target_placement_ids
Exemple #11
0
"""This code example gets a company by its id. To determine which companies
exist, run get_all_companies.py."""

__author__ = '[email protected] (Stan Grinberg)'

# Locate the client library. If module was installed via "setup.py" script, then
# the following two lines are not needed.
import os
import sys
sys.path.append(os.path.join('..', '..', '..', '..'))

# Import appropriate classes from the client library.
from adspygoogle.dfp.DfpClient import DfpClient

# Initialize client object.
client = DfpClient(path=os.path.join('..', '..', '..', '..'))

# Initialize appropriate service. By default, the request is always made against
# the sandbox environment.
company_service = client.GetCompanyService('https://sandbox.google.com',
                                           'v201010')

# Set the id of the company to get.
company_id = 'INSERT_COMPANY_ID_HERE'

# Get company.
company = company_service.GetCompany(company_id)[0]

# Display results.
print('Company with id \'%s\', name \'%s\', and type \'%s\' was found.' %
      (company['id'], company['name'], company['type']))
# See the License for the specific language governing permissions and
# limitations under the License.
"""This code example gets all roles. This sample can be used to determine which
role id is needed when getting and creating users."""

__author__ = '[email protected] (Stan Grinberg)'

# Locate the client library. If module was installed via "setup.py" script, then
# the following two lines are not needed.
import os
import sys
sys.path.append(os.path.join('..', '..', '..', '..'))

# Import appropriate classes from the client library.
from adspygoogle.dfp.DfpClient import DfpClient

# Initialize client object.
client = DfpClient(path=os.path.join('..', '..', '..', '..'))

# Initialize appropriate service. By default, the request is always made against
# sandbox environment.
user_service = client.GetUserService('https://sandbox.google.com', 'v201101')

# Get all roles.
roles = user_service.GetAllRoles()

# Display results.
for role in roles:
    print('Role with id \'%s\' and name \'%s\' was found.' %
          (role['id'], role['name']))
"""This example gets all cities available to target."""

__author__ = '[email protected] (Stan Grinberg)'

# Locate the client library. If module was installed via "setup.py" script, then
# the following two lines are not needed.
import os
import sys
sys.path.append(os.path.join('..', '..', '..', '..'))

# Import appropriate classes from the client library.
from adspygoogle.dfp.DfpClient import DfpClient


# Initialize client object.
client = DfpClient(path=os.path.join('..', '..', '..', '..'))

# Initialize appropriate service. By default, the request is always made against
# sandbox environment.
pql_service = client.GetPublisherQueryLanguageService(
    'https://sandbox.google.com', 'v201103')

select_statement = {'query': 'SELECT * FROM City WHERE targetable = true'}

# Get cities by statement.
result_set = pql_service.Select(select_statement)[0]

# Display results.
if result_set:
  column_labels = [label.values()[0] for label in result_set['columnTypes']]
  print 'Columns are: %s' % ', '.join(column_labels)
Exemple #14
0

def main(client):
    # Initialize appropriate service.
    company_service = client.GetService('CompanyService',
                                        'https://www.google.com', 'v201203')

    # Create company objects.
    companies = [{
        'name': 'Advertiser #%s' % Utils.GetUniqueName(),
        'type': 'ADVERTISER'
    }, {
        'name': 'Agency #%s' % Utils.GetUniqueName(),
        'type': 'AGENCY'
    }]

    # Add companies.
    companies = company_service.CreateCompanies(companies)

    # Display results.
    for company in companies:
        print(
            'Company with ID \'%s\', name \'%s\', and type \'%s\' was created.'
            % (company['id'], company['name'], company['type']))


if __name__ == '__main__':
    # Initialize client object.
    dfp_client = DfpClient(path=os.path.join('..', '..', '..', '..', '..'))
    main(dfp_client)
exist, run get_all_placements.py."""

__author__ = '[email protected] (Stan Grinberg)'

# Locate the client library. If module was installed via "setup.py" script, then
# the following two lines are not needed.
import os
import sys

sys.path.append(os.path.join('..', '..', '..', '..'))

# Import appropriate classes from the client library.
from adspygoogle.dfp.DfpClient import DfpClient

# Initialize client object.
client = DfpClient(path=os.path.join('..', '..', '..', '..'))

# Initialize appropriate service. By default, the request is always made against
# sandbox environment.
placement_service = client.GetPlacementService('https://sandbox.google.com',
                                               'v201010')

# Set the id of the placement to get.
placement_id = 'INSERT_PLACEMENT_ID_HERE'

# Get placement.
placement = placement_service.GetPlacement(placement_id)[0]

# Display results.
print('Placement with id \'%s\', name \'%s\', and status \'%s\' was found.' %
      (placement['id'], placement['name'], placement['status']))
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Settings and configuration for the unit tests."""

__author__ = '[email protected] (Stan Grinberg)'

import os
import sys
sys.path.append(os.path.join('..', '..', '..'))

from adspygoogle.common import SOAPPY
from adspygoogle.common import ZSI
from adspygoogle.dfp.DfpClient import DfpClient


HTTP_PROXY = None
SERVER_V201004 = 'https://sandbox.google.com'
SERVER_V201010 = 'https://sandbox.google.com'
SERVER_V201101 = 'https://sandbox.google.com'
SERVER_V201103 = 'https://sandbox.google.com'
VERSION_V201004 = 'v201004'
VERSION_V201010 = 'v201010'
VERSION_V201101 = 'v201101'
VERSION_V201103 = 'v201103'
client = DfpClient(path=os.path.join('..', '..', '..'))
client.soap_lib = ZSI
__author__ = '[email protected] (Stan Grinberg)'

# Locate the client library. If module was installed via "setup.py" script, then
# the following two lines are not needed.
import os
import sys
sys.path.append(os.path.join('..', '..', '..', '..'))

# Import appropriate classes from the client library.
from adspygoogle.dfp import DfpUtils
from adspygoogle.dfp.DfpClient import DfpClient


# Initialize client object.
client = DfpClient(path=os.path.join('..', '..', '..', '..'))

# Initialize appropriate service. By default, the request is always made against
# sandbox environment.
line_item_service = client.GetLineItemService(
    'https://sandbox.google.com', 'v201010')

# Set the id of the order to get line items from.
order_id = 'INSERT_ORDER_ID_HERE'

# Create query.
query = 'WHERE orderId = \'%s\' AND status = \'NEEDS_CREATIVES\'' % order_id

# Get line items by statement.
line_items = DfpUtils.GetAllEntitiesByStatement(client, 'LineItem', query)
for line_item in line_items:
Exemple #18
0
__author__ = '[email protected] (Stan Grinberg)'

# Locate the client library. If module was installed via "setup.py" script, then
# the following two lines are not needed.
import os
import sys
sys.path.append(os.path.join('..', '..', '..', '..'))

# Import appropriate classes from the client library.
from adspygoogle.common import Utils
from adspygoogle.dfp.DfpClient import DfpClient


# Initialize client object.
client = DfpClient(path=os.path.join('..', '..', '..', '..'))

# Initialize appropriate service. By default, the request is always made against
# sandbox environment.
creative_service = client.GetCreativeService(
    'https://sandbox.google.com', 'v201101')

# Set id of the advertiser (company) that all creatives will be assigned to.
advertiser_id = 'INSERT_ADVERTISER_COMPANY_ID_HERE'

# Create creative objects.
creatives = []
image_data = open(os.path.join('..', '..', 'tests', 'data',
    'medium_rectangle.jpg').replace('\\', '/'), 'r').read()
for i in xrange(5):
  creative = {
Exemple #19
0
get_all_line_items.py. To determine which creatives exit, run
get_all_creatives.py."""

__author__ = '[email protected] (Stan Grinberg)'

# Locate the client library. If module was installed via "setup.py" script, then
# the following two lines are not needed.
import os
import sys
sys.path.append(os.path.join('..', '..', '..', '..'))

# Import appropriate classes from the client library.
from adspygoogle.dfp.DfpClient import DfpClient

# Initialize client object.
client = DfpClient(path=os.path.join('..', '..', '..', '..'))

# Initialize appropriate service. By default, the request is always made against
# the sandbox environment.
lica_service = client.GetLineItemCreativeAssociationService(
    'https://sandbox.google.com', 'v201101')

# Set line item and creative id to use to retrieve the LICA.
line_item_id = 'INSERT_LINE_ITEM_ID_HERE'
creative_id = 'INSERT_CREATIVE_ID_HERE'

# Get LICA.
lica = lica_service.GetLineItemCreativeAssociation(line_item_id,
                                                   creative_id)[0]

# Display results.
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example gets the current network that you can make requests against."""

__author__ = '[email protected] (Stan Grinberg)'

# Locate the client library. If module was installed via "setup.py" script, then
# the following two lines are not needed.
import os
import sys
sys.path.append(os.path.join('..', '..', '..', '..'))

# Import appropriate classes from the client library.
from adspygoogle.dfp.DfpClient import DfpClient

# Initialize client object.
client = DfpClient(path=os.path.join('..', '..', '..', '..'))

# Initialize appropriate service. By default, the request is always made against
# the sandbox environment.
network_service = client.GetNetworkService('https://sandbox.google.com',
                                           'v201103')

# Get the current network.
network = network_service.GetCurrentNetwork()[0]

# Display results.
print('Current network has network code \'%s\' and display name \'%s\'.' %
      (network['networkCode'], network['displayName']))
Exemple #21
0
__author__ = '[email protected] (Stan Grinberg)'

# Locate the client library. If module was installed via "setup.py" script, then
# the following two lines are not needed.
import os
import sys

sys.path.append(os.path.join('..', '..', '..', '..'))

# Import appropriate classes from the client library.
from adspygoogle.common import Utils
from adspygoogle.dfp.DfpClient import DfpClient

# Initialize client object.
client = DfpClient(path=os.path.join('..', '..', '..', '..'))

# Initialize appropriate service. By default, the request is always made against
# the sandbox environment.
order_service = client.GetOrderService('https://sandbox.google.com', 'v201004')

# Create statement object to get all orders.
filter_statement = {'query': 'LIMIT 500'}

# Get orders by statement.
orders = order_service.GetOrdersByStatement(filter_statement)[0]['results']

if orders:
    # Update each local order object by changing its notes.
    updated_orders = []
    for order in orders:
Exemple #22
0
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Settings and configuration for the unit tests."""

__author__ = '[email protected] (Stan Grinberg)'

import os
import sys
sys.path.append(os.path.join('..', '..', '..'))

from adspygoogle.common import SOAPPY
from adspygoogle.common import ZSI
from adspygoogle.dfp.DfpClient import DfpClient

HTTP_PROXY = None
SERVER_V201004 = 'https://sandbox.google.com'
SERVER_V201010 = 'https://sandbox.google.com'
SERVER_V201101 = 'https://sandbox.google.com'
SERVER_V201103 = 'https://sandbox.google.com'
VERSION_V201004 = 'v201004'
VERSION_V201010 = 'v201010'
VERSION_V201101 = 'v201101'
VERSION_V201103 = 'v201103'
client = DfpClient(path=os.path.join('..', '..', '..'))
client.soap_lib = ZSI