实现过程: Python发送请求获得微信公众号返回的json数据,微信公众号接口看这里。利用Python的requests包发送post请求返回json数据,解析出来需要的字段,利用阿里云的pyODPS包,写入阿里云的maxcompute
代码如下:
from odps import ODPS
from odps.models import Schema, Column, Partition
import requests
import json
import datetime
import redis
#参数定义
#r = redis.StrictRedis(host='redishost,password='redispassword', port=6379,db=1, decode_responses=True)
# access_token =r.get('foo')
access_token = "xxxxxxxxxxxxxxx"
ds = (datetime.datetime.now() + datetime.timedelta(days=-1)).strftime('%Y%m%d')
qureydate=(datetime.datetime.now() + datetime.timedelta(days=-1)).strftime('%Y-%m-%d')
o = ODPS('accesskey', 'Iaccessid',
project='projectname', endpoint='http://service.odps.aliyun.com/api')
#删除分区数据
t_articletotal=o.get_table('wechat_articletotal')
t_articletotal.delete_partition('ds=' + ds, if_exists=True)
para = {
"begin_date": str(qureydate),
"end_date": str(qureydate)
}
def get_articletotal():
url_articletotal = "https://api.weixin.qq.com/datacube/getarticletotal?access_token=" + access_token
response = requests.post(url=url_articletotal, json=para)
data=response.text
try:
lists=json.loads(data)['list']
for i in lists:
ref_date=datetime.datetime.strptime(i['ref_date'], "%Y-%m-%d") #数据的日期
msgid=i['msgid'] #图文消息id
title=i['title'] #图文消息标题
user_source=i['user_source'] #代表用户从哪里进入来阅读该图文。0:会话;1.好友;2.朋友圈;3.腾讯微博;4.历史消息页;5.其他
for j in i['details']:
stat_date=j['stat_date']
target_user=j['target_user']
int_page_read_user=j['int_page_read_user'] #图文页(点击群发图文卡片进入的页面)的阅读人数
int_page_read_count=j['int_page_read_count'] #图文页的阅读次数
ori_page_read_user=j['ori_page_read_user'] #原文页(点击图文页“阅读原文”进入的页面)的阅读人数,无原文页时此处数据为0
ori_page_read_count=j['ori_page_read_count'] #原文页的阅读次数
share_user=j['share_user'] #分享的场景1代表好友转发 2代表朋友圈 3代表腾讯微博 255代表其他
share_count=j['share_count'] #分享的次数
add_to_fav_user=j['add_to_fav_user'] #收藏的人数
add_to_fav_count=j['add_to_fav_count'] #收藏的次数
records_articletotal=(ref_date,msgid,title,user_source,stat_date,target_user,int_page_read_user,int_page_read_count,ori_page_read_user,ori_page_read_count,share_user,share_count,add_to_fav_user,add_to_fav_count)
o.write_table('wechat_articletotal', records_articletotal, partition='ds=' + ds, create_partition=True)
print('articletotal写入成功')
except Exception as e:
print(e)
if __name__ == '__main__':
get_articletotal()
如果要用阿里的dataphin调度Python任务,同时Python需要用到第三方包,比如Redis,可以通过创建shell脚本实现,在dataphin的研发界面,数据处理创建一个shell任务,代码如下.
顺便吐槽一下,用的居然是Python2.7,前面要加# -*- coding:utf-8*-,而且每次都要先装第三方包。。。。。。
#安装第三方Python包。
pip install -i https://mirrors.aliyun.com/pypi/simple/ \
redis
#指定的python源写入至wechat_data_etl.py。
cat >wechat_data_etl.py <<EOF
----上面的Python代码-----
EOF
#python中调用文件。
python wechat_data_etl.py