百度统计项目部署记录

编写run.py文件

查看代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# coding=UTF-8(等号换为”:“也可以)
import requests
import time, datetime
import json

# 开始统计的日期
start_date = '20230520'
date = datetime.datetime.now()
# 结束统计的日期
end_date = str(date.year) + (str(date.month) if date.month > 9 else ('0' + str(date.month))) + (str(date.day) if date.day > 9 else ('0' + str(date.day)))
# token和siteid
access_token = '121.xxx'
site_id = '191xxx'
# 百度统计API
dataUrl = 'https://openapi.baidu.com/rest/2.0/tongji/report/getData?access_token=' + access_token + '&site_id=' + site_id
# 统计访问次数 PV 填写 'pv_count',统计访客数 UV 填写 'visitor_count',二选一
metrics = 'pv_count'
config = json.load(open('./token.json'))


def downFile(url, fileName, prefix='./'):
print('downloading :', url)
res = requests.get(url)
res = json.loads(res.content)

if('error_code' in res.keys()):
update(prefix=prefix)
downFile(url, fileName, prefix)
with open(prefix+fileName, 'w') as f:
json.dump(res, f)
print('writing :', prefix+fileName)

def update(prefix, url='http://openapi.baidu.com/oauth/2.0/token?grant_type=refresh_token&refresh_token=' + config['refresh'] + '&client_id=' + config['api_key'] + '&client_secret=' + config['serect_key']):
res = requests.get(url)
res = json.loads(res.content)
print(res)

config['access'] = res['access_token']
config['refresh'] = res['refresh_token']
with open(prefix + 'token.json', 'w') as f:
json.dump(config, f)

# 访客地图
downFile(dataUrl + '&start_date=' + start_date + '&end_date=' + end_date + '&metrics=' + metrics + '&method=visit/district/a',
'map.json')

# 访问趋势
downFile(dataUrl + '&start_date=' + start_date + '&end_date=' + end_date + '&metrics=' + metrics + '&method=trend/time/a&gran=month',
'trends.json')

# 访问来源
downFile(dataUrl + '&start_date=' + start_date + '&end_date=' + end_date + '&metrics=' + metrics + '&method=source/all/a',
'sources.json')

## 搜索引擎
downFile(dataUrl + '&start_date=' + start_date + '&end_date=' + end_date + '&metrics=' + metrics + '&method=source/engine/a',
'engine.json')

## 外部链接
downFile(dataUrl + '&start_date=' + start_date + '&end_date=' + end_date + '&metrics=' + metrics + '&method=source/link/a',
'link.json')

# 访问日历
'''
访问日历需要获取一年内的数据,按照一年365天计算,大概为52周多一点,所以前面有完整的52排,获取方式只要通过开始日期年份-1即可
然后就是第53排的处理,python中的date.weekday()获取的星期几是0对应周一,所以通过(date.weekday()+1)%7即可转换到0对应周日
于是在52周的基础上,减去星期数,就可以得到新的start_date
'''
date = datetime.datetime(date.year-1, date.month, date.day)
date = datetime.datetime.fromtimestamp(date.timestamp()-3600*24*((date.weekday()+1)%7))
start_date = str(date.year) + (str(date.month) if date.month > 9 else ('0' + str(date.month))) + (str(date.day) if date.day > 9 else ('0' + str(date.day)))
downFile(dataUrl + '&method=overview/getTimeTrendRpt' + '&metrics=' + metrics + '&start_date=' + start_date + '&end_date=' + end_date,
'calendar.json')

运行run.py

  1. 把run.py放到服务器目录下

  2. 新建token.json用于保存需要的密钥信息

    查看代码
    1
    2
    3
    4
    5
    6
    7
    {
    "access": "121.xxx", //百度统计ACCESS_TOKEN
    "refresh": "122.xxx", //百度统计REFRESH_TOKEN
    "site_id": "191xxx", //百度统计网站id
    "api_key": "3rHxxx", //百度统计API Key
    "serect_key": "ELIxxx" //百度统计Secret Key
    }
  3. 运行run.py

    查看代码测试
    1
    python3 run.py
  4. 运行之后自动生成若干个json文件用于储存百度统计数据

新建定时任务

  1. 我用的是宝塔,在计划任务里面新增shell脚本

  2. 填好任务名称、执行周期

  3. 编写脚本内容,保存后执行一次看是否成功

    查看代码
    1
    2
    cd /www/wwwroot/baidu_tongji
    python3 run.py
  4. cron额外命令

    查看代码
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    //CentOS6上的cron命令
    service crond start //启动服务
    service crond stop //关闭服务
    service crond restart //重启服务
    service crond reload //重新载入配置
    service crond status //查看状态
    //CentOS7上的cron命令
    systemctl start crond.service //启动服务
    systemctl stop crond.service //关闭服务
    systemctl restart crond.service //重启服务
    systemctl reload crond.service //重新载入配置
    systemctl status crond.service //查看状态

站点跨域配置

打开站点设置配置伪静态

查看代码
1
2
3
4
5
6
7
8
9
10
11
//localhost:4000是为了博客本地调试
location / {
if ($http_origin ~* (http://localhost:4000|https://你的域名.com)) {
add_header Access-Control-Allow-Origin '$http_origin';
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
}
if ($request_method = 'OPTIONS') {
return 204;
}
}

参考文章

  1. Hexo 博客访问日历图
  2. 博客成长日志 | 准实时访问统计