-
Notifications
You must be signed in to change notification settings - Fork 1
/
sender.py
283 lines (265 loc) · 9.77 KB
/
sender.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
#coding=utf-8
from __future__ import absolute_import
__author__ = 'xiyuanbupt'
import datetime
import logging
import logging.config
logging.config.fileConfig('./logger.ini')
from jinja2 import Environment,PackageLoader
from pymongo import MongoClient
import requests
import time,threading
from conf_util import ConfUtil
env = Environment(loader=PackageLoader('m_interact','templates'))
'''
用于向接口中推送数据,每天会在固定的时间启动一个 sender 进程,用来推送当前的数据
'''
client = MongoClient(ConfUtil.getMongoIP(),ConfUtil.getMongoPort())
db = client[ConfUtil.getDBName()]
class Sender:
klAudio = db[ConfUtil.getKLAudioCollectionName()]
xmlyAudio = db[ConfUtil.getXMLYAudioCollectionName()]
qtAudio = db[ConfUtil.getQTAudioCollectionName()]
template = env.get_template('sendTemp.xml')
soapTargetUri = ConfUtil.getSoapTargetUri()
def __init__(self):
pass
def useJinja(self):
template = env.get_template('sendTemp.xml')
return template.render(PGMGUID = 'wwww')
#从数据库中读取所有未被推送到cnr 并且媒体文件已经被下载的数据项
def getXMLYAudioNotInCNRWithFile(self):
'''
获得所有未被推送到CNR 但是媒体文件已经被下载的 audio
'''
with self.xmlyAudio.find(
{
"sendToCNRTime":None,
"audioDownloadDir":{"$ne":None}
}
) as cursor:
for audio in cursor:
yield audio
def getKLAudioNotInCNRWithFile(self):
'''
获得所有未被推送到CNR 但是媒体文件已经被下载的audio
'''
with self.klAudio.find(
{
"sendToCNRTime":None,
"audioDownloadDir":{"$ne":None}
}
) as cursor:
for audio in cursor:
yield audio
def getQTAudioNotInCNRWithFile(self):
'''
获得未被推送到cnr 但是媒体文件已经被下载的audio,qt 网站
:return:
'''
with self.qtAudio.find(
{
"sendToCNRTime":None,
"audioDownloadDir":{"$ne":None}
}
) as cursor:
for audio in cursor:
yield audio
def getXMLContentFromAudio(self,sourceWeb,audio):
'''
从audio 中获得 xml 内容
函数会根据 sourceWeb 的不同来决定推送的逻辑
sourceWeb 为 kl xmly 或者 qt
audio 为直接从 数据库中取到的对应网站audio 的字典格式
'''
now = datetime.datetime.now()
RequestID = audio.get('uuid',None)
RequestTime = now.strftime("%Y-%m-%d %H:%M:%S")
TaskGUID = audio.get('uuid',None)
TaskName = audio.get('album_title',None)
PutinTime = now.strftime("%Y-%m-%d %H:%M:%S")
uuid = audio.get('uuid',None)
SoapTargetUri = self.soapTargetUri.format(
sourceWeb = sourceWeb,uuid = uuid
)
PGMNAME = TaskName
PGMGUID = audio.get('uuid',None)
Title = TaskName
#如下代码之后需要重构,已经将sourceWeb 写死在,故并不通用
if sourceWeb == 'kl':
CATALOGNAME = u'考拉fm\点播\{category}\{album}'.format(
category = audio.get('category_title',u'未知'),
album = audio.get('album_title',u'未知')
)
CreatorName = audio.get('uploaderName',u'北邮爬虫').strip()
PgmNote = audio.get('fullDescs',u'描述未知')
FileName = audio.get('audioDownloadDir',None)
elif sourceWeb == 'xmly':
CATALOGNAME = u'喜马拉雅fm\点播\{category}\{album}'.format(
category = audio.get('category_title',u'未知'),
album = audio.get('album_title',u'未知')
)
CreatorName = audio.get('uploadUserName',u'北邮爬虫').strip()
PgmNote = audio.get('intro',u'描述未知')
FileName = audio.get('audioDownloadDir',None)
elif sourceWeb == 'qt':
CATALOGNAME = u'蜻蜓fm\点播\{category}\{album}'.format(
category = audio.get('category_title',u'未知类别'),
album = audio.get('album_title',u'未知专辑')
)
CreatorName = u'蜻蜓fm,作者未知'
PgmNote = audio.get('audioName',u'描述未知')
FileName = audio.get('audioDownloadDir',None)
else:
print u'未知sourceWeb'
xmlContent = self.template.render(
RequestID = RequestID,
RequestTime = RequestTime,
TaskGUID = TaskGUID,
PutinTime = PutinTime,
uuid = uuid,
SoapTargetUri = SoapTargetUri,
PGMNAME = PGMNAME,
PGMGUID = PGMGUID,
Title = Title,
CATALOGNAME = CATALOGNAME,
CreatorName = CreatorName,
PgmNote = PgmNote,
FileName = FileName,
TaskName = TaskName,
firstplaytime = None,
broadstarttime = None,
broadendtime = None
)
return xmlContent
def sendXMLToCNR(self,xml):
'''
将xml 内容推送到cnr
:param xml:
:return:
'''
headers = {'Content-Type':'application/xml'}
res = requests.post(ConfUtil.getCnrUri(),data=xml.encode('utf-8'),
headers = headers)
return res
def getAudioPutToCNR(self,count = 10000,funAfterPush = lambda:time.sleep(0)):
'''
冷启动,或者平时使用,向cnr 发送当前数据库中有媒体文件但是未被发送到cnr 的数据
执行获得所有未被推送到cnr ,并且文件已经被下载到本地种的audio 并将其推送至cnr
并更改标志位
:param count 为本次期望发送到cnr 最大的音频数量,默认为10,生产环境中需要更改
:param funAfterPush 每次执行推送任务之后的函数
'''
logger = logging.getLogger('sender')
#每个网站推送相同的数据量
count = count/3
xcount , qcount , kcount = count,count,count
xmlyAudios = self.getXMLYAudioNotInCNRWithFile()
for xmlyAudio in xmlyAudios:
xcount -= 1
if xcount < 0:
break
xmlContent = self.getXMLContentFromAudio('xmly',xmlyAudio)
resp = self.sendXMLToCNR(xmlContent)
#需要添加根据返回的状态判断相关信息
if True:
logger.info(
u'send xmlyAudio uuid - {0}'.format(
xmlyAudio['uuid']
)
)
#设置将数据推送到cnr 的时间
funAfterPush()
self.xmlyAudio.update(
{
"_id":xmlyAudio['_id']
},
{
"$set":{
"sendToCNRTime":datetime.datetime.now()
}
}
)
klAudios = self.getKLAudioNotInCNRWithFile()
for klAudio in klAudios:
kcount -= 1
if kcount < 0:
break
xmlContent = self.getXMLContentFromAudio('kl',klAudio)
resp = self.sendXMLToCNR(xmlContent)
if True:
logger.info(
u'send klAudio uuid - {0}'.format(
klAudio['uuid']
)
)
#设置推送到cnr 的时间
funAfterPush()
self.klAudio.update(
{
"_id":klAudio['_id']
},
{
"$set":{
"sendToCNRTime":datetime.datetime.now()
}
}
)
qtAudios = self.getQTAudioNotInCNRWithFile()
for qtAudio in qtAudios:
qcount -= 1
if qcount < 0:
break
xmlContent = self.getXMLContentFromAudio('qt',qtAudio)
resp = self.sendXMLToCNR(xmlContent)
if True:
logger.info(
u'send qtAudio uuid - {0}'.format(
qtAudio['uuid']
)
)
funAfterPush()
self.qtAudio.update(
{
"_id":qtAudio['_id']
},
{
"$set":{
"sendToCNRTime":datetime.datetime.now()
}
}
)
# def dict_to_xml(self,tag,d):
# '''
# Trun a simple dict of key/value pairs into XML
# :param tag:
# :param d:
# :return:
# '''
# elem = Element(tag)
# for key,val in d.items():
# if type(val) == type({}):
# elem.append(self.dict_to_xml(key,val))
# else:
# child = Element(key)
# child.text = str(val)
# elem.append(child)
# return elem
# 一次向cnr 推送 setting 中的数目的 audio
class pushThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
sender = Sender()
sleepSec = ConfUtil.getSleepSecAgterPush()
sender.getAudioPutToCNR(ConfUtil.getCnrSendCountOnce(),
lambda:time.sleep(sleepSec))
if __name__ == "__main__":
threadCount = ConfUtil.getSendThreadCount()
threads = []
for i in range(threadCount):
thread = pushThread()
thread.start()
threads.append(thread)
for t in threads:
t.join()