GithubHelp home page GithubHelp logo

Comments (1)

sedhha avatar sedhha commented on May 29, 2024

Fixed it by preventing default client credentials loading:

class DV360Reports:

    def __init__(self, query_id, outputdirectory, cfg, reportWindow = 12, disableAutoCredentialDetect = True):

        self.cfg = cfg
        self.arguments = self.get_arguments()
        self.outputdir = outputdirectory
        self.reportWindow = reportWindow
        self.apiSecrets = cfg.path["bidManagerSecrets"]
        self.disableAutoCredentialDetect = disableAutoCredentialDetect
        #print(self.outputdir)



    def get_arguments(self, argv = sys.argv, desc = __doc__, parents=None):

        parent_parsers = [tools.argparser]
        if parents:
            parent_parsers.extend(parents)

        parser = argparse.ArgumentParser(
            description=desc,
            formatter_class=argparse.RawDescriptionHelpFormatter,
            parents=parent_parsers)
        return parser.parse_args(argv[1:])


    def setup(self, flags, secretsPath = None):

        if secretsPath == None:
            secretsPath = self.apiSecrets

        API_NAME = 'doubleclickbidmanager'
        API_VERSION = 'v1.1'
        CREDENTIAL_STORE_FILE = API_NAME + '.dat'

        credentials = self.load_application_default_credentials()

        if credentials is None:
            client_secrets = secretsPath
            storage = oauthFile.Storage(CREDENTIAL_STORE_FILE)
            credentials = self.load_user_credentials(client_secrets, storage, flags)

        # Authorize HTTP object with the prepared credentials.
        http = credentials.authorize(http=httplib2.Http())

        # Construct and return a service object via the discovery service.
        return discovery.build(API_NAME, API_VERSION, http=http)


    def load_application_default_credentials(self):

        if self.disableAutoCredentialDetect:
            return None
        
        API_SCOPES = ['https://www.googleapis.com/auth/doubleclickbidmanager']

        try:
            credentials = client.GoogleCredentials.get_application_default()
            return credentials.create_scoped(API_SCOPES)

        except client.ApplicationDefaultCredentialsError:
            pass


    def load_user_credentials(self,client_secrets, storage, flags):

        API_SCOPES = ['https://www.googleapis.com/auth/doubleclickbidmanager']

        flow = client.flow_from_clientsecrets(
            client_secrets,
            scope=API_SCOPES,
            message=tools.message_if_missing(client_secrets))

        credentials = storage.get()
        if credentials is None or credentials.invalid:
            credentials = tools.run_flow(flow, storage, flags)

        return credentials


    def performDownload(self, query_id, report_window = None, output_dir = None):

        if report_window == None:
            report_window = self.reportWindow

        if report_window != None:
            self.reportWindow = report_window


        doubleclick_bid_manager = self.setup(self.arguments)

        if output_dir != None:

            self.outputdir = output_dir

        if output_dir == None:
            output_dir = self.outputdir

        if query_id:
            query = (
                doubleclick_bid_manager.queries().getquery(queryId=query_id).execute())
            
            try:

                if (self.is_in_report_window(query['metadata']['latestReportRunTimeMs'],
                                        report_window)):
                                        if not os.path.isabs(output_dir):
                                            output_dir = os.path.expanduser(output_dir)

                                        report_url = query['metadata']['googleCloudStoragePathForLatestReport']
                                        output_file = '%s/%s.csv' % (output_dir, query['queryId'])
                                        with open(output_file, 'wb') as output:
                                            with closing(urlopen(report_url)) as url:
                                                output.write(url.read())
                                        return pd.read_csv(output_file,low_memory=False,encoding= 'unicode_escape')
                else:
                    print("Comes under else")
                    print('No reports for queryId "%s" in the last %s hours.' %
                        (query['queryId'], report_window))

            except KeyError:
                print('No report found for queryId "%s".' % query_id)

        else:
            response = doubleclick_bid_manager.queries().listqueries().execute()
            print('Id\t\tName')
            if 'queries' in response:
                self.print_queries(response)
                # Then everything else
                while 'nextPageToken' in response and response['nextPageToken']:
                    
                    response = doubleclick_bid_manager.queries().listqueries(
                        pageToken=response['nextPageToken']).execute()
                    self.print_queries(response)
            else:
                print('No queries exist.')

        return False


    


    def print_queries(self, response):

        for q in response['queries']:
            print('%s\t%s' % (q['queryId'], q['metadata']['title']))


    def is_in_report_window(self, run_time_ms, report_window):
        report_time = datetime.fromtimestamp(int((run_time_ms)) / 1000)
        earliest_time_in_range = datetime.now() - timedelta(hours=report_window)
        return report_time > earliest_time_in_range

from googleads-bidmanager-examples.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.