Hi, 

Forgive me if this is a very trivial question. 

I am trying to use the TargetingIdeaService to get kw suggestions. 
This was working fine with when I run single threaded it runs fine, but 
when run multi threaded it fails with error: "Unable to parse SOAP buffer 
for outgoing messages. not well-formed (invalid token): line 1, column 0"

I am using  *adspygoogle*=1.1.6* api_version*=v201309

//keywords.py attachment contains GoogleKeywords class

Code Snippet:---
    import threading
    import datetime

    class ThreadClass(threading.Thread):
        def __init__(self, url):
            threading.Thread.__init__(self)
            self._url = url

        def run(self):
            CLIENT_ID = 'xxxx'
            CLIENT_SECRET = 'xxxxx'
            REFRESH_TOKEN = 'xxxx'
            credentials = OAuth2Credentials(
                access_token='--expired--',
                client_id=CLIENT_ID,
                client_secret=CLIENT_SECRET,
                refresh_token=REFRESH_TOKEN,
                token_expiry=None,
                token_uri='https://accounts.google.com/o/oauth2/token',
                user_agent='xxxx')
            credentials.refresh(httplib2.Http())
            headers = {
                "userAgent"        : 'xxxx',
                "developerToken"   : 'xxxx',
                "validateOnly"     : "n",
                "oauth2credentials": credentials,
                "clientCustomerId" : 'xxxx'
            }

            client_config = {
            "soap_lib"   : adspygoogle.common.soappy,
            "compress"   : "y",
            "xml_parser" : adspygoogle.common.ETREE,
            "debug"      : "n",
            "raw_debug"  : "n",
            }

            client = AdWordsClient(headers=headers, config=client_config)
            targeting_idea_service = 
client.GetTargetingIdeaService('https://adwords.google.com')
            keywords = GoogleKeywords(None,targeting_idea_service) //Class 
is implemented in keywords.py
            print keywords.getRelatedKeywordsForUrl(self._url)

    urls = 
['http://www.hardtail-mtb.com/specialized-s-works-stumpjumper-fsr-carbon-evo-mountain-bike-2014-full-suspension-mtb.html',
            
'http://www.hardtail-mtb.com/rocky-mountain-element-970-rsl-bike-2013.html',
            
'http://www.hardtail-mtb.com/specialized-s-works-stumpjumper-fsr-carbon-evo-mountain-bike-2014-full-suspension-mtb.html',
            
'http://www.hardtail-mtb.com/rocky-mountain-element-970-rsl-bike-2013.html']

    for i in range(4):
        t = ThreadClass(urls[i])
        t.start()

-- 
-- 
=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~
Also find us on our blog and Google+:
https://googleadsdeveloper.blogspot.com/
https://plus.google.com/+GoogleAdsDevelopers/posts
=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~

You received this message because you are subscribed to the Google
Groups "AdWords API Forum" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/adwords-api?hl=en
--- 
You received this message because you are subscribed to the Google Groups 
"AdWords API Forum" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/d/optout.
#!/usr/bin/python

class GoogleKeywords(object):
    """All auth check, and actual client connection, should be done outside this
    class. This only abstracts out the purely keyword retrieval part."""
    def __init__(self, logger, targeting_idea_service):
        self._logger = logger
        self.targeting_idea_service = targeting_idea_service

    def _doQuery(self, selector, qname):
        """run the query in selector, within a loop if necessary, to get back
        all results.
        @return a dictionary with the keyword as a key, and related attributes
        as a dictionary of attribute name and value
        """
        offset = 0
        PAGE_SIZE = 100
        selector['paging'] = {'startIndex': str(offset),
                              'numberResults': str(PAGE_SIZE)}
        more_pages = True
        kws = {}
        while more_pages:
            #try:
            page = self.targeting_idea_service.Get(selector)[0]
            #except Exception as e:
                #self._logger.error('Google API fatal error: %s', str(e))
                #return kws
            print ''
            if 'entries' in page:
                for result in page['entries']:
                    attributes = {}
                    for attribute in result['data']:
                        if attribute['key'] == 'KEYWORD_TEXT':
                            kw = attribute['value']['value']
                        if attribute['key'] == 'AVERAGE_CPC':
                            attributes['AVERAGE_CPC'] = attribute['value'].get('value', {}).get('microAmount', '')                         
                        else:
                            attributes[attribute['key']] = attribute['value'].get('value', '')
                    kws[kw] = attributes
            else:
                self._logger.debug('No related keywords were found for url %s'%(url))
            offset += PAGE_SIZE
            selector['paging']['startIndex'] = str(offset)
            more_pages = offset < int(page['totalNumEntries'])
        
        return kws
    
    
    def getRelatedKeywordsForUrl(self, url):
        """get keywords for url "url". targeting_idea_service is an instance of
        the Adwords TargetingIdeaService client
        @return a dictionary with the keyword as a key, and related attributes
        as a dictionary of attribute name and value
        """
        offset = 0
        selector = {'searchParameters': 
                    [{
                    'xsi_type': 'RelatedToUrlSearchParameter',
                    'urls': [url]
                    },
                     {
                    # Language setting (optional).
                    # The ID can be found in the documentation:
                    #  https://developers.google.com/adwords/api/docs/appendix/languagecodes
                    'xsi_type': 'LanguageSearchParameter',
                    'languages': [{'id': '1000'}]
                    },
                     ],
                    'ideaType': 'KEYWORD',
                    'requestType': 'IDEAS',
                    'requestedAttributeTypes': ['KEYWORD_TEXT', 'SEARCH_VOLUME',
                                                'CATEGORY_PRODUCTS_AND_SERVICES',
                                                'AVERAGE_CPC', 'COMPETITION']
                    }
        return self._doQuery(selector, "url: %s" % url)
    

    def getRelatedKeywords(self, keyword):
        """
        Get related keywords from google for the given keyword, using broad
        match
        http://code.google.com/apis/adwords/docs/reference/latest/TargetingIdeaService.TargetingIdeaSelector.html
        """
        selector = {
            'searchParameters': [{
                    'xsi_type': 'RelatedToQuerySearchParameter',
                    'queries': [keyword]
                    }],
            'ideaType': 'KEYWORD',
            'requestType': 'IDEAS',
            # get the same data as requested for getRelatedkeywordsforurl
            'requestedAttributeTypes': ['KEYWORD_TEXT', 'SEARCH_VOLUME',
                                        'CATEGORY_PRODUCTS_AND_SERVICES',
                                        'AVERAGE_CPC', 'COMPETITION'],
            'paging': {
                'startIndex': '0',
                'numberResults': '100'
                }
            }
        return self._doQuery(selector, "keyword: %s" % keyword)

Reply via email to