def main(client, asset_name, path_to_file, in_stream_video_creative_id, asset_to_replace): # Initialize appropriate service. creative_service = client.GetCreativeService( 'https://advertisersapitest.doubleclick.net', 'v1.19') # Convert file into format that can be sent in SOAP messages. content = Utils.ReadFile(path_to_file) content = base64.encodestring(content) # Create the In-Stream video creative asset. in_stream_video_asset = { 'name': asset_name, 'content': content, } # Create an upload request to make this asset a media file for an existing # In-Stream creative. in_stream_asset_upload_request = { 'companion': 'true', 'inStreamAsset': in_stream_video_asset, 'creativeId': in_stream_video_creative_id } # Replace the existing asset with a newly uploaded asset. result = creative_service.ReplaceInStreamAsset( asset_to_replace, in_stream_asset_upload_request)[0] # Display a success message. print( 'Replaced companion ad asset \'%s\' in In-Stream video creative with ' 'ID \'%s\'.' % (asset_to_replace, result['id']))
def main(client, asset_name, path_to_file, in_stream_video_creative_id): # Initialize appropriate service. creative_service = client.GetCreativeService( 'https://advertisersapitest.doubleclick.net', 'v1.19') # Convert file into format that can be sent in SOAP messages. content = Utils.ReadFile(path_to_file) content = base64.encodestring(content) # Create the In-Stream video creative asset. in_stream_video_asset = { 'name': asset_name, 'content': content, } # Create an upload request to make this asset a media file for an existing # In-Stream creative. in_stream_asset_upload_request = { 'mediaFile': 'true', 'inStreamAsset': in_stream_video_asset, 'creativeId': in_stream_video_creative_id } # Save the media file. result = creative_service.UploadInStreamAsset( in_stream_asset_upload_request)[0] # Display a success message. print('Added a media file to In-Stream video creative with ID \'%s\'.' % result['Id'])
def testUpperStackLogging(self): """Tests whether we can define logger at client level and log before and after the API request is made. """ logger = logging.getLogger(self.__class__.__name__) logger.setLevel(logging.DEBUG) fh = logging.FileHandler(self.__class__.TMP_LOG) fh.setLevel(logging.DEBUG) logger.addHandler(fh) # Clean up temporary log file. Utils.PurgeLog(self.__class__.TMP_LOG) logger.debug(self.__class__.DEBUG_MSG1) advertiser_service = client.GetAdvertiserService( self.__class__.SERVER, self.__class__.VERSION, HTTP_PROXY) advertiser_service.GetAdvertisers({}) logger.debug(self.__class__.DEBUG_MSG2) data = Utils.ReadFile(self.__class__.TMP_LOG) self.assertEqual(data.find(self.__class__.DEBUG_MSG1), 0) self.assertEqual(data.find(self.__class__.DEBUG_MSG2), len(self.__class__.DEBUG_MSG1) + 1) # Clean up and remove temporary log file. Utils.PurgeLog(self.__class__.TMP_LOG) os.remove(self.__class__.TMP_LOG)
def testCallRawMethod(self): """Test whether we can call an API method by posting SOAP XML message.""" soap_message = Utils.ReadFile( os.path.join('data', 'request_getusersbystatement.xml')) url = '/apis/ads/publisher/v201103/UserService' http_proxy = None self.failUnlessRaises(DfpApiError, client.CallRawMethod, soap_message, url, self.__class__.SERVER, http_proxy)
def testCallRawMethod(self): """Test whether we can call an API method by posting SOAP XML message.""" soap_message = Utils.ReadFile( os.path.join('data', 'request_getallcampaigns.xml')) url = '/api/adwords/cm/v201008/CampaignService' http_proxy = None self.failUnlessRaises(AdWordsApiError, client.CallRawMethod, soap_message, url, self.__class__.SERVER, http_proxy)
def testCallRawMethod(self): """Test whether we can call an API method by posting SOAP XML message.""" soap_message = Utils.ReadFile( os.path.join('data', 'request_getaccountinfo.xml')) url = '/api/adwords/v13/AccountService' http_proxy = HTTP_PROXY self.failUnlessRaises(AdWordsApiError, client.CallRawMethod, soap_message, url, self.__class__.SERVER, http_proxy)
def testReplaceRichMediaCreativePackage(self): """Test whether we can replace the mtf for the creative.""" if self.__class__.test_rich_media: if self.__class__.richmedia_package is None: self.testUploadRichMediaCreativePackage() content = Utils.ReadFile(os.path.join('..', 'data', 'Inpage.mtf')) content = base64.encodestring(content) self.assert_(isinstance( self.__class__.service.ReplaceRichMediaCreativePackage( self.__class__.richmedia_package['id'], content), tuple))
def testUploadRichMediaCreativePackage(self): """Test whether we can upload the mtf file creative the RichMedia creative.""" if self.__class__.test_rich_media: advertiser_id = self.__class__.campaign['advertiserId'] content = Utils.ReadFile(os.path.join('..', 'data', 'Inpage.mtf')) content = base64.encodestring(content) rich_media = self.__class__.service.UploadRichMediaCreativePackage( advertiser_id, content, 'False') self.__class__.richmedia_package = upload_request[0] self.assert_(isinstance(rich_media, tuple))
def testCallRawMethod(self): """Test whether we can call an API method by posting SOAP XML message.""" soap_message = Utils.ReadFile( os.path.join(__file__[:__file__.rfind('/')], '..', 'data', 'request_getadvertisers.xml')) url = '/v1.16/api/dfa-api/advertiser' http_proxy = None self.assert_( isinstance( client.CallRawMethod(soap_message, url, self.__class__.SERVER, http_proxy), tuple))
def testUploadNetworkWidgetImage(self): """Test whether we can upload a widget backup image.""" image = Utils.ReadFile(os.path.join('..', 'data', 'code_logo.gif')) image = base64.encodestring(image) widget_image_upload_request = { 'network': self.__class__.user_self['networkId'], 'filedata': image, 'filename': 'testImage.gif', 'networkWidgetImageUpload': 'true' } self.assert_(isinstance( self.__class__.service.UploadNetworkWidgetImage( widget_image_upload_request), tuple))
def testUploadRichMediaAsset(self): """Test whether we can upload a RichMedia asset.""" if self.__class__.test_rich_media: content = Utils.ReadFile(os.path.join('..', 'data', 'Inpage.mtf')) content = base64.encodestring(content) upload_request = { 'assetFileName': 'RichmediaAsset%s.mtf' % Utils.GetUniqueName(), 'fileData': content } upload_request = self.__class__.service.UploadRichMediaAsset( upload_request) self.__class__.richmedia_asset = upload_request[0] self.assert_(isinstance(upload_request, tuple))
def testSaveCreativeAsset(self): """Test whether we can save a creative asset.""" advertiser_id = self.__class__.campaign['advertiserId'] content = Utils.ReadFile(os.path.join('..', 'data', 'code_logo.gif')) content = base64.encodestring(content) creative_asset = { 'name': 'CreativeAsset%s.gif' % Utils.GetUniqueName(), 'advertiserId': advertiser_id, 'forHTMLCreatives': 'false', 'content': content, } creative_asset = self.__class__.service.SaveCreativeAsset(creative_asset) self.__class__.creative_asset = creative_asset[0] self.assert_(isinstance(creative_asset, tuple))
def testError502(self): """Test whether we can handle and report 502 errors.""" buf = DfaSoapBuffer() html_code = Utils.ReadFile( os.path.join('..', 'data', 'http_error_502.html')) buf.write(html_code) if not buf.IsHandshakeComplete(): data = buf.GetBufferAsStr() else: data = '' self.assertEqual(Utils.GetErrorFromHtml(data), self.__class__.TRIGGER_MSG)
def testReplaceRichMediaAsset(self): """Test whether we can replace a RichMedia asset with the object passed.""" if self.__class__.test_rich_media: if self.__class__.richmedia_asset is None: self.testUploadRichMediaAsset() content = Utils.ReadFile(os.path.join('..', 'data', 'Inpage.mtf')) content = base64.encodestring(content) replace_request = { 'assetFileName': 'RichmediaAsset%s.mtf' % Utils.GetUniqueName(), 'creativeId': self.__class__.richmedia_asset['id'], 'fileData': content } self.assert_(isinstance( self.__class__.service.ReplaceRichMediaAsset( self.__class__.richmedia_asset['childAssets'][0]['fileName'], replace_request), tuple))
def testError502(self): """Test whether we can handle and report 502 errors.""" # Temporarily redirect STDOUT into a buffer. buf = AdWordsSoapBuffer() sys.stdout = buf html_code = Utils.ReadFile(os.path.join('data', 'http_error_502.html')) print html_code # Restore STDOUT. sys.stdout = sys.__stdout__ if not buf.IsHandshakeComplete(): data = buf.GetBufferAsStr() else: data = '' self.assertEqual(Utils.GetErrorFromHtml(data), self.__class__.TRIGGER_MSG)
def main(client, advertiser_id, asset_name, path_to_file): # Initialize appropriate service. creative_service = client.GetCreativeService( 'https://advertisersapitest.doubleclick.net', 'v1.20') # Convert file into format that can be sent in SOAP messages. content = Utils.ReadFile(path_to_file) content = base64.encodestring(content) # Construct and save mobile asset. image_asset = { 'name': asset_name, 'advertiserId': advertiser_id, 'content': content, 'forHTMLCreatives': 'true' } result = creative_service.SaveCreativeAsset(image_asset)[0] # Display results. print('Creative asset with file name of \'%s\' was created.' % result['savedFilename'])
class MediaServiceTestV201101(unittest.TestCase): """Unittest suite for MediaService using v201101.""" SERVER = SERVER_V201101 VERSION = VERSION_V201101 IMAGE_DATA = Utils.ReadFile(os.path.join('data', 'image.jpg')) if client.soap_lib == SOAPPY: IMAGE_DATA = base64.encodestring(IMAGE_DATA) client.debug = False service = None def setUp(self): """Prepare unittest.""" print self.id() if not self.__class__.service: self.__class__.service = client.GetMediaService( self.__class__.SERVER, self.__class__.VERSION, HTTP_PROXY) def testGetAllImageMedia(self): """Test whether we can fetch all existing image media.""" selector = { 'fields': ['MediaId', 'Type'], 'predicates': [{ 'field': 'Type', 'operator': 'EQUALS', 'values': ['IMAGE'] }] } self.assert_(isinstance(self.__class__.service.Get(selector), tuple)) def testUploadImageMedia(self): """Test whether we can upload new image media.""" media = [{ 'xsi_type': 'Image', 'data': self.__class__.IMAGE_DATA, 'type': 'IMAGE', 'name': 'Sample Image' }] self.assert_(isinstance(self.__class__.service.Upload(media), tuple))
def main(client, image_filename): # Initialize appropriate service. media_service = client.GetMediaService(version='v201406') image_data = Utils.ReadFile(image_filename) image_data = base64.encodestring(image_data) # Construct media and upload image. media = [{'xsi_type': 'Image', 'data': image_data, 'type': 'IMAGE'}] media = media_service.Upload(media)[0] # Display results. if media: dimensions = Utils.GetDictFromMap(media['dimensions']) print( 'Image with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\' was' ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], dimensions['FULL']['width'], media['mimeType'])) else: print 'No images were uploaded.' print print('Usage: %s units, %s operations' % (client.GetUnits(), client.GetOperations()))
def CreateTestCreative(client, server, version, advertiser_id): """Create a test creative. Args: client: DfpClient used for service creation. server: str the API server. version: str the API version. advertiser_id: str the company ID for the creative's advertiser. Returns: The ID of the creative. """ creative_service = client.GetService('CreativeService', server, version) # Create creative object. image_data = Utils.ReadFile( os.path.join(__file__[:__file__.rfind('/')], '..', 'data', 'medium_rectangle.jpg')) image_data = base64.encodestring(image_data) creative = { 'type': 'ImageCreative', 'name': 'Image Creative #%s' % Utils.GetUniqueName(), 'advertiserId': advertiser_id, 'destinationUrl': 'http://google.com', 'imageName': 'image.jpg', 'imageByteArray': image_data, 'size': { 'width': '300', 'height': '250' } } # Add creatives. creatives = creative_service.CreateCreatives([creative]) return creatives[0]['id']
import sys sys.path.append(os.path.join('..', '..', '..', '..')) # Import appropriate constants and classes from the client library. from adspygoogle.adwords import MIN_API_VERSION from adspygoogle.common import Utils from adspygoogle.adwords.AdWordsClient import AdWordsClient from adspygoogle.adwords.AdWordsErrors import AdWordsApiError # Initialize AdWordsClient object. client = AdWordsClient(path=os.path.join('..', '..', '..', '..')) # Construct SOAP message by loading XML from existing data file. soap_message = Utils.ReadFile( os.path.join('..', '..', '..', '..', 'tests', 'adspygoogle', 'adwords', 'data', 'request_getaccountinfo.xml')) server = 'https://adwords-sandbox.google.com' url = '/api/adwords/%s/AccountService' % MIN_API_VERSION http_proxy = None try: response = client.CallRawMethod(soap_message, url, server, http_proxy)[0] # Display results. print 'Response:\n%s' % response except AdWordsApiError, e: print 'Note: this should fail, unless you\'ve set valid authentication data.' print raise e
def testDownloadCsvReportNonAscii(self): """Test whether we can download a csv report that includes non-ASCII data using.""" xml = Utils.ReadFile(os.path.join('data', 'report_non_ascii.xml')) self.assert_(isinstance(self.__class__.service.DownloadCsvReport( self.__class__.COMPLETED_REPORT_JOB_ID, xml), (str, unicode)))
sys.path.append(os.path.join('..', '..', '..', '..')) # Import appropriate classes from the client library. from adspygoogle.adwords.AdWordsClient import AdWordsClient from adspygoogle.common import SOAPPY from adspygoogle.common import Utils # Initialize client object. client = AdWordsClient(path=os.path.join('..', '..', '..', '..')) # Initialize appropriate service. media_service = client.GetMediaService( 'https://adwords-sandbox.google.com', 'v201101') image_data = Utils.ReadFile('INSERT_IMAGE_PATH_HERE') if client.soap_lib == SOAPPY: image_data = base64.encodestring(image_data) # Construct media and upload image. media = [{ # TODO: SOAPpy needs an xsi_type here, but SOAPpy has other problems 'data': image_data, 'type': 'IMAGE' }] media = media_service.Upload(media)[0] # Display results. if media: dimensions = Utils.GetDictFromMap(media['dimensions']) # WARNING: SOAPpy turns the dimensions field into a list, so this won't work
print ' [+] %s' % os.path.join(os.path.abspath(target['location']), target['group']) else: print ' [+] %s' % os.path.abspath(target['location']) # Fetch service types and their attributes. print 'Generating service types from client interface ...' group_holders = {} for target in API_TARGETS: if 'group' not in target: continue for f_name in os.listdir(os.path.abspath(target['location'])): f_path = os.path.join(os.path.abspath(target['location']), f_name) if f_path.find('_services_types.py') < 0 or f_path.endswith('pyc'): continue data = Utils.ReadFile(f_path) for type in re.compile('class (\w+)_Def\(').findall(data): pattern = re.compile('(class %s_Def\(.*?\):.*?\n\n)' % (type), re.MULTILINE | re.DOTALL) holders = pattern.findall(data) if not holders: continue schema = re.compile('schema = "(.*?)"').findall(holders[0])[0] schema_group = schema.split('/')[-2] schema_sig = '%s|%s' % (schema_group, schema) attributes = re.compile('aname="_(.*?)"').findall(holders[0]) if not attributes: continue if schema_sig not in group_holders: group_holders[schema_sig] = {'ns': schema, 'types': []} has_type = False