⬆️ ⬇️

Getting statistics for all clients from the Yandex Direct API API in the context of days using Python

I often use short statistics in the context of days in my work to track traffic deviations.



For more information on writing requests, he wrote in the article “Receiving Yandex Direct Advertising Campaigns Using APIs in DataFrame (Python)” .



In this article I will talk more about how to structure data and queries so that you can use it normally.

')

We should register the request to the server as a function.



Personally, I made 2 files: the function with the request and the file with the data that will be passed to the function.



In the first file we write the function.



I request the same fields for all projects, so I need to transfer only the date, login and token to the request.



Data transfer to my function looks like this:



def rep(token,login,date_from,date_to): 


We write a request to the server API Yandex Direct



This request requests data on the following parameters:





The final file with the request



Code
 import requests from requests.exceptions import ConnectionError from time import sleep import json #        UTF-8   Python 3,    Python 2 import sys def rep(token,login,date_from,date_to): if sys.version_info < (3,): def u(x): try: return x.encode("utf8") except UnicodeDecodeError: return x else: def u(x): if type(x) == type(b''): return x.decode('utf8') else: return x # ---   --- #   Reports   JSON- () ReportsURL = 'https://api.direct.yandex.com/json/v5/reports' # OAuth- ,       token = token #     #  ,        clientLogin = login # ---   --- #  HTTP-  headers = { # OAuth-.   Bearer  "Authorization": "Bearer " + token, #     "Client-Login": clientLogin, #    "Accept-Language": "ru", #    "processingMode": "auto" #      # "returnMoneyInMicros": "false", #            # "skipReportHeader": "true", #         # "skipColumnHeader": "true", #          # "skipReportSummary": "true" } #    body = { "params": { "SelectionCriteria": { "DateFrom": date_from, "DateTo": date_to }, "FieldNames": [ "Date", "Impressions", "Clicks", "Ctr", "Cost", "AvgCpc", "AvgImpressionPosition", "AvgClickPosition", "AvgTrafficVolume", "BounceRate", "AvgPageviews", ], "ReportName": u("Report4"), "ReportType": "ACCOUNT_PERFORMANCE_REPORT", "DateRangeType": "CUSTOM_DATE", "Format": "TSV", "IncludeVAT": "NO", "IncludeDiscount": "NO" } } #     JSON body = json.dumps(body, indent=4) # ---      --- #   HTTP- 200,     #   HTTP- 201  202,    while True: try: req = requests.post(ReportsURL, body, headers=headers) req.encoding = 'utf-8' #      UTF-8 if req.status_code == 400: print("         ") print("RequestId: {}".format(req.headers.get("RequestId", False))) print("JSON- : {}".format(u(body))) print("JSON-  : \n{}".format(u(req.json()))) break elif req.status_code == 200: format(u(req.text)) break elif req.status_code == 201: print("       ") retryIn = int(req.headers.get("retryIn", 60)) print("    {} ".format(retryIn)) print("RequestId: {}".format(req.headers.get("RequestId", False))) sleep(retryIn) elif req.status_code == 202: print("    ") retryIn = int(req.headers.get("retryIn", 60)) print("    {} ".format(retryIn)) print("RequestId: {}".format(req.headers.get("RequestId", False))) sleep(retryIn) elif req.status_code == 500: print("    . ,    ") print("RequestId: {}".format(req.headers.get("RequestId", False))) print("JSON-  : \n{}".format(u(req.json()))) break elif req.status_code == 502: print("     .") print( ",     -      .") print("JSON- : {}".format(body)) print("RequestId: {}".format(req.headers.get("RequestId", False))) print("JSON-  : \n{}".format(u(req.json()))) break else: print("  ") print("RequestId: {}".format(req.headers.get("RequestId", False))) print("JSON- : {}".format(body)) print("JSON-  : \n{}".format(u(req.json()))) break #  ,       API  except ConnectionError: #         print("     API") #     break #   -   except: #         print("  ") #     break json_string = json.dumps(body) return req.text 




2 File



We take out the dates, logins and tokens separately as variables.



Like that:



 # mytoken='blablablablaBLABLAsdfgsrgkdfgnf' # project = 'elama-99999999' # DateFrom="2019-04-08" DateTo="2019-04-16" 


This is done in order to easily change the information on all customers, and the dates of the reports.



Code for requesting project statistics



 print( '\n=== ===') data=rep(mytoken,project,DateFrom,DateTo) file=open("cashe.csv","w") file.write(data) file.close() f=DataFrame.from_csv("cashe.csv",header=1,sep=' ',index_col=0,parse_dates=True) f['Cost']=f['Cost']*1.2 f['Cost']=f['Cost']/1000000 f['AvgCpc']=f['AvgCpc']*1.2 f['AvgCpc']=f['AvgCpc']/1000000 print(f) 


More details:



  1. The name of the project ("=" is used for better selection, so that you do not get lost in the information)
  2. Data - Write to this line variables that are already identified above. (this line will execute the first file)
  3. Write the server response to a file
  4. Open the file as a DataFrame
  5. Add to the monetary value of the VAT.
  6. We translate monetary values ​​into ordinary rubles (standardly, the API does not use rubles, but rubles * 1,000,000.
  7. We derive our DataFrame






The second file looks like this:



Code
 # import pandas as pd import numpy as np from pandas import Series,DataFrame from     import rep #   pd.set_option('display.max_columns',None) pd.set_option('display.expand_frame_repr',False) pd.set_option('max_colwidth',-1) # mytoken='blablablablaBLABLAsdfgsrgkdfgnf' # project = 'elama-99999999' # DateFrom="2019-04-08" DateTo="2019-04-16" print( '\n=== ===') data=rep(mytoken,project,DateFrom,DateTo) file=open("cashe.csv","w") file.write(data) file.close() f=DataFrame.from_csv("cashe.csv",header=1,sep=' ',index_col=0,parse_dates=True) f['Cost']=f['Cost']*1.2 f['Cost']=f['Cost']/1000000 f['AvgCpc']=f['AvgCpc']*1.2 f['AvgCpc']=f['AvgCpc']/1000000 print(f) 




We register all projects in the second file, after which we should display statistics on all projects.



After we need only change the time interval in the fields DateFrom and DateTo.

Source: https://habr.com/ru/post/449392/



All Articles