Google analytics使用python与postgresql集成,表不';t填充
我正试图使用Python将我的Google Analytics数据上传到我的postgres数据库中,然而,我遇到了一个我真的不知道如何解决的问题,这是Python的新手 首先,我使用一段代码使用psycopg2获取一维和两个度量:Google analytics使用python与postgresql集成,表不';t填充,python,postgresql,google-analytics,psycopg2,Python,Postgresql,Google Analytics,Psycopg2,我正试图使用Python将我的Google Analytics数据上传到我的postgres数据库中,然而,我遇到了一个我真的不知道如何解决的问题,这是Python的新手 首先,我使用一段代码使用psycopg2获取一维和两个度量: if traffic_results.get('rows', []): for row in traffic_results.get('rows'): #print(row) cursor.execute("""INSERT INTO tr
if traffic_results.get('rows', []):
for row in traffic_results.get('rows'):
#print(row)
cursor.execute("""INSERT INTO traffic (yearMonth, users, sessions)
VALUES(%s, %s, %s)""", [row[0], row[1], row[2]])
else:
print('No Rows Found')
但是,在创建了一个新表“traffic1”并尝试返回具有更多维度和度量的数据后,它会打印“未找到行”
如果有任何关于可能出错的提示,我将不胜感激。多谢各位
编辑这是我正在使用的完整代码:
import psycopg2
import sys
from googleapiclient.errors import HttpError
from googleapiclient import sample_tools
from oauth2client.service_account import ServiceAccountCredentials
from httplib2 import Http
from apiclient.discovery import build
#Main
def main():
# Authenticate and create the service for the Core Reporting API
credentials = ServiceAccountCredentials.from_json_keyfile_name(
'xxxxxx.json',
['https://www.googleapis.com/auth/analytics.readonly'])
http_auth = credentials.authorize(Http())
service = build('analytics', 'v3', http=http_auth)
# Define the connection string and connect
conn_string = "xxx' port=xxx
dbname='GA' user='admin' password='password'"
conn = psycopg2.connect(conn_string)
# Open a cursor
cursor = conn.cursor()
# Run the query function using the API service
traffic_results = get_api_traffic_query(service).execute()
# Insert each row of the result set
if traffic_results.get('rows', []):
for row in traffic_results.get('rows'):
#print(row)
cursor.execute("""INSERT INTO traffic0 (campaign, device, impressions, clicks, ctr)
VALUES(%s, %s, %s, %s, %s)""", [row[0], row[1], row[2], row[3], row[4]])
else:
print('No Rows Found')
# Commit changes
conn.commit()
# Select and retrieve results
#cursor.execute("SELECT * FROM traffic0")
#records = cursor.fetchall()
#print(records)
# Close the cursor and the connection
cursor.close()
conn.close()
# Query function
def get_api_traffic_query(service):
return service.data().ga().get(
ids='ga:xxxxxx',
start_date='2017-01-01',
end_date='2017-01-31',
metrics='ga:impressions,ga:adClicks,ga:CTR',
dimensions='ga:campaign,ga:deviceCategory',
# sort='-ga:yearMonth',
# filters='ga:pagePath=~signup',
segment='sessions::condition::ga:hostname!~mongo|app|help|docs|staging|googleweblight',
start_index='1',
max_results='25')
if __name__ == '__main__':
main()
显然
if traffic_results.get('rows', []):
是
False
,因此执行else:
子句体。这意味着Google Analytics的响应中没有键行
,或者是一个空列表。检查响应(甚至打印到stdout)并检查有哪些键,以及响应是否包含错误。什么是流量\u结果
?它看起来像一本字典。请提供用于定义/创建它的代码。另外,请修复您的缩进。谢谢,似乎响应返回了一个空列表,我不理解这一点,因为使用谷歌查询浏览器,相同的维度和指标会返回正常结果。如果您正确查询了指标,请仔细检查分析文档。
if traffic_results.get('rows', []):