彼は、 「DataFrameでAPIを使用してYandex.Directダイレクトダイレクトキャンペーンを取得する(Python)」という記事に、リクエストの作成について詳しく書いています。
この記事では、データとクエリを正常に使用できるように構造化する方法について詳しく説明します。
サーバーリクエストを関数として登録する必要があります。
個人的には、2つのファイルを作成しました。1つはリクエストを含む関数で、もう1つは関数に転送されるデータを含むファイルです。
最初のファイルに関数を書きます
すべてのプロジェクトに同じフィールドを要求するため、日付、ログイン、トークンのみを要求に転送する必要があります。
私に関数にデータを渡すのは次のようになります。
def rep(token,login,date_from,date_to):
Yandex.Direct APIサーバーにリクエストを書いています
このクエリは、次のパラメーターのデータを要求します。
- 日付
- 印象
- クリック数
- Ctr
- 費用
- Avgcpc
- AvgImpressionPosition
- AvgClickPosition
- AvgTrafficVolume
- 直帰率
- AvgPageviews
最終リクエストファイル
コード
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ファイル
日付、ログイン、トークンを変数として個別に取り出します。
このようなもの:
# 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)
詳細:
- プロジェクトの名前(「=」は、情報が失われないように、より適切な選択のために使用します)
- データ-すでに上記で示した変数をこの行に書き込みます。 (この行は最初のファイルを実行します)
- サーバーの応答をファイルに書き込みます
- ファイルをDataFrameとして開きます
- VATの金額に追加します。
- 金額を通常のルーブルに変換します(標準として、APIはルーブルを使用せず、ルーブル* 1,000,000を使用します。
- DataFrameを出力します

2番目のファイルは次のとおりです。
コード
# 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)
すべてのプロジェクトを2番目のファイルに書き込みます。その後、すべてのプロジェクトの統計を表示する必要があります。
その後、DateFromフィールドとDateToフィールドで時間の長さを変更するだけです。