BingAds / BingAds-Python-SDK

Other
116 stars 162 forks source link

Unable to download report via python sdk #140

Closed sathiz1993 closed 4 years ago

sathiz1993 commented 4 years ago

I have tried to download a report from bing via python. I have executed the report_requests.py file. I am using python 3.6 and bingads 13.0.1. While downloading the report it returns the following error.

suds.WebFault: Server raised fault: 'The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter 
https://bingads.microsoft.com/Reporting/v13:ReportRequest. The InnerException message was 'Error in line 1 position 3434. Expecting state 'Element'.. Encountered 'Text'  with name '', namespace ''. '.  Please see InnerException for more details.
qitia commented 4 years ago

@sathiz1993 can you please share trackingid thus I can investigate?

sathiz1993 commented 4 years ago

Hi @qitia . This is my trackingid "461a99a4-62f3-49ab-b303-fff9c4a24f48" . I am able to access my accounts but unable to get the report of the campaign. Please help me out with some sample snippet

qitia commented 4 years ago

from the log I can only see you tried to download report at about 2019-12-19 10:35:48.5031994(UTC time), and you are using SDK version 11.12.2. the exception is "1093JUXXXXXXXXX7 should migrate to the reporting api v13." which means your devtoken "1093JUXXXXXXXXX7" is not in V12 allow list. could you please double check if you are still using V12?

The trackingid you provided is not the one you call reporting api, it is something when you try authenticate...

sathiz1993 commented 4 years ago

Hello @qitia . I have not using v12 anywhere in my code and also I am using the latest bing python sdk. When I try to call this function its return error. Authentication flow works fine

reporting_service_manager.download_report(reporting_download_parameters)

It returns the following error. Error message shown in debug mode

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><s:Fault><faultcode xmlns:a="http://schemas.microsoft.com/net/2005/12/windowscommunicationfoundation/dispatcher">a:DeserializationFailed</faultcode><faultstring xml:lang="en-US">The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter https://bingads.microsoft.com/Reporting/v13:ReportRequest. The InnerException message was \'Error in line 1 position 3434. Expecting state \'Element\'.. Encountered \'Text\'  with name \'\', namespace \'\'. \'.  Please see InnerException for more details.</faultstring><detail><ExceptionDetail xmlns="http://schemas.datacontract.org/2004/07/System.ServiceModel" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><HelpLink i:nil="true"/><InnerException><HelpLink i:nil="true"/><InnerException i:nil="true"/><Message>Error in line 1 position 3434. Expecting state \'Element\'.. Encountered \'Text\'  with name \'\', namespace \'\'. </Message><StackTrace>   at ReadArrayOfCampaignReportScopeFromXml(XmlReaderDelegator , XmlObjectSerializerReadContext , XmlDictionaryString , XmlDictionaryString , CollectionDataContract )&#xD;\n   at System.Runtime.Serialization.CollectionDataContract.ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)&#xD;\n   at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, Type declaredType, DataContract&amp; dataContract)&#xD;\n   at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 id, RuntimeTypeHandle declaredTypeHandle, String name, String ns)&#xD;\n   at ReadAccountThroughCampaignReportScopeFromXml(XmlReaderDelegator , XmlObjectSerializerReadContext , XmlDictionaryString[] , XmlDictionaryString[] )&#xD;\n   at System.Runtime.Serialization.ClassDataContract.ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)&#xD;\n   at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, Type declaredType, DataContract&amp; dataContract)&#xD;\n   at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 id, RuntimeTypeHandle declaredTypeHandle, String name, String ns)&#xD;\n   at ReadCampaignPerformanceReportRequestFromXml(XmlReaderDelegator , XmlObjectSerializerReadContext , XmlDictionaryString[] , XmlDictionaryString[] )&#xD;\n   at System.Runtime.Serialization.ClassDataContract.ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)&#xD;\n   at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, Type declaredType, DataContract&amp; dataContract)&#xD;\n   at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, String name, String ns)&#xD;\n   at System.Runtime.Serialization.DataContractSerializer.InternalReadObject(XmlReaderDelegator xmlReader, Boolean verifyObjectName, DataContractResolver dataContractResolver)&#xD;\n   at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)&#xD;\n   at System.Runtime.Serialization.DataContractSerializer.ReadObject(XmlDictionaryReader reader, Boolean verifyObjectName)&#xD;\n   at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.PartInfo.ReadObject(XmlDictionaryReader reader, XmlObjectSerializer serializer)&#xD;\n   at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.DeserializeParameterPart(XmlDictionaryReader reader, PartInfo part, Boolean isRequest)</StackTrace><Type>System.Runtime.Serialization.SerializationException</Type></InnerException><Message>The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter https://bingads.microsoft.com/Reporting/v13:ReportRequest. The InnerException message was \'Error in line 1 position 3434. Expecting state \'Element\'.. Encountered \'Text\'  with name \'\', namespace \'\'. \'.  Please see InnerException for more details.</Message><StackTrace>   at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.DeserializeParameterPart(XmlDictionaryReader reader, PartInfo part, Boolean isRequest)&#xD;\n   at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.DeserializeParameters(XmlDictionaryReader reader, PartInfo[] parts, Object[] parameters, Boolean isRequest)&#xD;\n   at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.DeserializeBody(XmlDictionaryReader reader, MessageVersion version, String action, MessageDescription messageDescription, Object[] parameters, Boolean isRequest)&#xD;\n   at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeBodyContents(Message message, Object[] parameters, Boolean isRequest)&#xD;\n   at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeRequest(Message message, Object[] parameters)&#xD;\n   at System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc&amp; rpc)&#xD;\n   at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&amp; rpc)&#xD;\n   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&amp; rpc)&#xD;\n   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc&amp; rpc)&#xD;\n   at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)</StackTrace><Type>System.ServiceModel.Dispatcher.NetDispatcherFaultException</Type></ExceptionDetail></detail></s:Fault></s:Body></s:Envelope>
qitia commented 4 years ago

hello @sathiz1993 , is this "1093JUXXXXXXXXX7" your devtoken?When did you made the call? from the log you provide I can not tell too much to investigate... Just looks like your request is not in a welformed xml, could you please double check?

qitia commented 4 years ago

@sathiz1993 any update? please share more info if you have for my investigation. Like when did you make the call, your devtoken.

sathiz1993 commented 4 years ago

Hello @qitia . Issue is resolved. Thanks for support

qitia commented 4 years ago

Glad to know it has been resolved. May I know what is the root cause?

sathiz1993 commented 4 years ago

scope.Campaigns.CampaignReportScope is invalid value This might cause the error

Dorsaf-Sdiri commented 2 years ago

I have the same exception : suds.WebFault: Server raised fault: 'The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter https://bingads.microsoft.com/AdInsight/v13:EntityIds. The InnerException message was 'Error in line 2 position 31. Expecting state 'Element'.. Encountered 'Text' with name '', namespace ''. '. Please see InnerException for more details.'

import urllib3
from bingads.v13.reporting import *
from bingads.service_client import ServiceClient
import numpy as np
from AdInsightExampleHelper import *
from CompaignManagmeentExampleHelper import *
from AuthHelper import *
#from CompaignManagmeentExampleHelper import output_status_message, output_array_of_campaign
from OutputHelper import *

# You must provide credentials in AuthHelper.py.
LOCAL_FILE = "./auction-insight-june-2022.csv"

def main(authorization_data):
    #try:
    campaigns = campaign_service.GetCampaignsByAccountId(
        AccountId=authorization_data.account_id,
        CampaignType=['Search'])

    entityIds = []
    #print(campaign_service.soap_client)
    output_status_message("Campaigns:")
    for c in campaigns['Campaign']:
        if 'Concurrents' in c.Name:
            entityIds.append(c.Id)
            print(c.Name)
    entityIds = np.array(entityIds)

    search_parameters = adinsight_service.factory.create('ArrayOfSearchParameter')

    date_range_search_parameter = adinsight_service.factory.create('DateRangeSearchParameter')
    end_date = adinsight_service.factory.create('DayMonthAndYear')
    end_date.Day = 30
    end_date.Month = 8
    end_date.Year = 2022

    start_date = adinsight_service.factory.create('DayMonthAndYear')
    start_date.Day = 1
    start_date.Month = 8
    start_date.Year = 2022

    date_range_search_parameter.EndDate = end_date
    date_range_search_parameter.StartDate = start_date
    #print(output_array_of_campaign(campaigns))
    auctionSegmentSearchParameter = adinsight_service.factory.create('AuctionSegmentSearchParameter')
    auctionSegment = adinsight_service.factory.create('AuctionSegment')
    auctionSegment.Day;
    auctionSegmentSearchParameter.Segment = auctionSegment.Week
    #AuctionInsightKpiAdditionalField = adinsight_service.factory.create('AuctionInsightKpiAdditionalField')
    #returnAdditionalFields = AuctionInsightKpiAdditionalField.AbsoluteTopOfPageRate;

    EntityType = campaign_service.factory.create('EntityType')

    search_parameters.SearchParameter.append([date_range_search_parameter,auctionSegmentSearchParameter])
    print(search_parameters)
    get_keyword_ideas_response = adinsight_service.GetAuctionInsightData(EntityType ='Campaign',EntityIds =entityIds, SearchParameters=search_parameters)
    keyword_ideas = get_keyword_ideas_response

    if keyword_ideas is None:
        output_status_message("No keyword ideas are available for the search parameters.")
        sys.exit(0)

    output_status_message("KeywordIdeas:")
    output_array_of_keywordidea(keyword_ideas)

    #except WebFault as ex:
    #    output_webfault_errors(ex)
    #except Exception as ex:
    #    output_status_message(ex)

def download_file(response):
    CHUNK = 16 * 1024
    with open(LOCAL_FILE, 'wb') as f:
        while True:
            chunk = response.read(CHUNK)
            if not chunk: break
            f.write(chunk)
            f.flush()

# Main execution
if __name__ == '__main__':
    #output_status_message("Loading the web service client proxies...")

    authorization_data = AuthorizationData(
        account_id=None,
        customer_id=None,
        developer_token=DEVELOPER_TOKEN,
        authentication=None,
    )

    campaign_service = ServiceClient(
        service='CampaignManagementService',
        version=13,
        authorization_data=authorization_data,
        environment=ENVIRONMENT,
    )
    adinsight_service = ServiceClient(
        service='AdInsightService',
        version=13,
        authorization_data=authorization_data,
        environment=ENVIRONMENT,
    )

    auth = AuthHelper(authorization_data)
    auth()

    main(authorization_data)

can you please help me understand it and fix it ?