-
Notifications
You must be signed in to change notification settings - Fork 15
/
poster.py
271 lines (239 loc) · 13.9 KB
/
poster.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
# -*- coding: utf-8 -*-
import sys
from os.path import abspath, dirname
sys.path.insert(0, dirname(abspath(__file__)))
sys.path.insert(0, dirname(dirname(abspath(__file__))))
import json
import pymysql
import pymysql.cursors
import const as ct
from base.clog import getLogger
from twisted.enterprise import adbapi
from hkex import HkexCrawler
from investor import InvestorCrawler
from investor import MonthInvestorCrawler
from plate_valuation import PlateValuationCrawler
from stock_limit_crawler import StockLimitCrawler
from china_treasury_rate import ChinaTreasuryRateCrawler
from china_security_industry_valuation import ChinaSecurityIndustryValuationCrawler
from pymysql.err import OperationalError, InterfaceError, DataError, InternalError, IntegrityError
logger = getLogger(__name__)
class Poster(object):
def __init__(self, item):
self.item = item
self.table = ''
def do_insert(self, cursor, item):
insert_sql, params = item.get_insert_sql(self.table)
cursor.execute(insert_sql, params)
def check(self):
if not ct.SPIDERMON_VALIDATION_ERRORS_FIELD in self.item: return True
errors = self.item[ct.SPIDERMON_VALIDATION_ERRORS_FIELD]
logger.error("%s check failed:%s" % (self.__class__, json.dumps(errors, indent=4)))
return False
def store(self):
raise NotImplementedError()
def get_hk_dbname(market, direction):
dbname = ''
if market == 'sse' and direction == 'north':
dbname = HkexCrawler.get_dbname(ct.SH_MARKET_SYMBOL, ct.HK_MARKET_SYMBOL)
elif market == 'sse' and direction == 'south':
dbname = HkexCrawler.get_dbname(ct.HK_MARKET_SYMBOL, ct.SH_MARKET_SYMBOL)
elif market == 'szse' and direction == 'south':
dbname = HkexCrawler.get_dbname(ct.HK_MARKET_SYMBOL, ct.SZ_MARKET_SYMBOL)
else:
dbname = HkexCrawler.get_dbname(ct.SZ_MARKET_SYMBOL, ct.HK_MARKET_SYMBOL)
return dbname
class HkexTradeOverviewPoster(Poster):
def __init__(self, item, dbinfo = ct.DB_INFO):
super(HkexTradeOverviewPoster, self).__init__(item)
self.mysql_reconnect_wait = 60
self.dbname = get_hk_dbname(market = item['market'], direction = item['direction'])
self.table = HkexCrawler.get_capital_table(self.dbname)
self.connect = pymysql.connect(host=dbinfo['host'], port=dbinfo['port'], db=self.dbname, user=dbinfo['user'], passwd=dbinfo['password'], charset=ct.UTF8)
self.cursor = self.connect.cursor()
#self.dbpool = adbapi.ConnectionPool("pymysql", host = dbinfo['host'], db = self.dbname, user = dbinfo['user'], password = dbinfo['password'], charset = "utf8", cursorclass = pymysql.cursors.DictCursor, use_unicode = True)
def on_error(self, failure):
args = failure.value.args
if failure.type in [OperationalError, InterfaceError]:
# <class 'pymysql.err.OperationalError'> (1045, "Access denied for user 'username'@'localhost' (using password: YES)")
# <class 'pymysql.err.OperationalError'> (2013, 'Lost connection to MySQL server during query ([Errno 110] Connection timed out)')
# <class 'pymysql.err.OperationalError'> (2003, "Can't connect to MySQL server on '127.0.0.1' ([WinError 10061] 由于目标计算机积极拒绝,无法连接。)")
# <class 'pymysql.err.InterfaceError'> (0, '') # after crawl started: sudo service mysqld stop
logger.info('MySQL: exception {} {}, Trying to recommit in {} sec'.format(failure.type, args, self.mysql_reconnect_wait))
# https://twistedmatrix.com/documents/12.1.0/core/howto/time.html
from twisted.internet import task
from twisted.internet import reactor
task.deferLater(reactor, self.mysql_reconnect_wait, self.async_store)
return
elif failure.type in [DataError, InternalError]:
# <class 'pymysql.err.DataError'> (1264, "Out of range value for column 'position_id' at row 2")
# <class 'pymysql.err.InternalError'> (1292, "Incorrect date value: '1977-06-31' for column 'release_day' at row 26")
logger.warn('MySQL: {} {} exception from item {}'.format(failure.type, args, item))
return
elif failure.type in [IntegrityError]:
# <class 'pymysql.err.IntegrityError'> (1048, "Column 'name' cannot be null") films 43894
if failure.value.args[0] != 1062:
logger.warn('MySQL: {} {} exception from some items'.format(failure.type, args))
return
else:
logger.error('MySQL: {} {} unhandled exception'.format(failure.type, args))
return
def async_store(self):
query = self.dbpool.runInteraction(self.do_insert, self.item)
query.addErrback(self.on_error)
def store(self):
try:
insert_sql, params = self.item.get_insert_sql(self.table)
if insert_sql == None and params == None: return
self.cursor.execute(insert_sql, params)
self.connect.commit()
except Exception as e:
logger.debug(e)
class HkexTradeTopTenItemPoster(Poster):
def __init__(self, item, dbinfo = ct.DB_INFO):
super(HkexTradeTopTenItemPoster, self).__init__(item)
self.mysql_reconnect_wait = 60
self.dbname = get_hk_dbname(market = item['market'], direction = item['direction'])
self.table = HkexCrawler.get_topten_table(self.dbname)
self.connect = pymysql.connect(host=dbinfo['host'], port=dbinfo['port'], db=self.dbname, user=dbinfo['user'], passwd=dbinfo['password'], charset=ct.UTF8)
self.cursor = self.connect.cursor()
#self.dbpool = adbapi.ConnectionPool("pymysql", host = dbinfo['host'], db = self.dbname, user = dbinfo['user'], password = dbinfo['password'], charset = "utf8", cursorclass = pymysql.cursors.DictCursor, use_unicode = True)
def on_error(self, failure):
args = failure.value.args
if failure.type in [OperationalError, InterfaceError]:
# <class 'pymysql.err.OperationalError'> (1045, "Access denied for user 'username'@'localhost' (using password: YES)")
# <class 'pymysql.err.OperationalError'> (2013, 'Lost connection to MySQL server during query ([Errno 110] Connection timed out)')
# <class 'pymysql.err.OperationalError'> (2003, "Can't connect to MySQL server on '127.0.0.1' ([WinError 10061] 由于目标计算机积极拒绝,无法连接。)")
# <class 'pymysql.err.InterfaceError'> (0, '') # after crawl started: sudo service mysqld stop
logger.info('MySQL: exception {} {}, Trying to recommit in {} sec'.format(failure.type, args, self.mysql_reconnect_wait))
# https://twistedmatrix.com/documents/12.1.0/core/howto/time.html
from twisted.internet import task
from twisted.internet import reactor
task.deferLater(reactor, self.mysql_reconnect_wait, self.store)
return
elif failure.type in [DataError, InternalError]:
# <class 'pymysql.err.DataError'> (1264, "Out of range value for column 'position_id' at row 2")
# <class 'pymysql.err.InternalError'> (1292, "Incorrect date value: '1977-06-31' for column 'release_day' at row 26")
if failure.value.args[0] != 1062:
logger.warn('MySQL: {} {} exception from item {}'.format(failure.type, args, item))
return
elif failure.type in [IntegrityError]:
# <class 'pymysql.err.IntegrityError'> (1048, "Column 'name' cannot be null") films 43894
logger.warn('MySQL: {} {} exception from some items'.format(failure.type, args))
return
else:
logger.error('MySQL: {} {} unhandled exception'.format(failure.type, args))
return
def async_store(self):
query = self.dbpool.runInteraction(self.do_insert, self.item)
query.addErrback(self.on_error)
def store(self):
try:
insert_sql, params = self.item.get_insert_sql(self.table)
if insert_sql == None and params == None: return
self.cursor.execute(insert_sql, params)
self.connect.commit()
except Exception as e:
logger.debug(e)
class MyDownloadItemPoster(Poster):
def __init__(self, item):
super(MyDownloadItemPoster, self).__init__(item)
class SPledgeSituationItemPoster(Poster):
def __init__(self, item):
super(SPledgeSituationItemPoster, self).__init__(item)
class ChinaSecurityIndustryValuationPoster(Poster):
def __init__(self, item, dbinfo = ct.DB_INFO, redis_host = None):
super(ChinaSecurityIndustryValuationPoster, self).__init__(item)
self.dbname = ChinaSecurityIndustryValuationCrawler.get_dbname()
self.table = ChinaSecurityIndustryValuationCrawler.get_tablename()
self.connect = pymysql.connect(host=dbinfo['host'], port=dbinfo['port'], db=self.dbname, user=dbinfo['user'], passwd=dbinfo['password'], charset=ct.UTF8)
self.cursor = self.connect.cursor()
def store(self):
try:
insert_sql, params = self.item.get_insert_sql(self.table)
if insert_sql == None and params == None: return
self.cursor.execute(insert_sql, params)
self.connect.commit()
except Exception as e:
logger.debug(e)
def on_error(self, failure):
if not (failure.type == IntegrityError and failure.value.args[0] == 1062):
logger.error(failure.type, failure.value, failure.getTraceback())
class ChinaTreasuryRateItemPoster(Poster):
def __init__(self, item, dbinfo = ct.DB_INFO, redis_host = None):
super(ChinaTreasuryRateItemPoster, self).__init__(item)
self.dbname = ChinaTreasuryRateCrawler.get_dbname()
self.table = ChinaTreasuryRateCrawler.get_tablename()
self.connect = pymysql.connect(host=dbinfo['host'], port=dbinfo['port'], db=self.dbname, user=dbinfo['user'], passwd=dbinfo['password'], charset=ct.UTF8)
self.cursor = self.connect.cursor()
def store(self):
try:
insert_sql, params = self.item.get_insert_sql(self.table)
if insert_sql == None and params == None: return
self.cursor.execute(insert_sql, params)
self.connect.commit()
except Exception as e:
logger.debug(e)
def on_error(self, failure):
if not (failure.type == IntegrityError and failure.value.args[0] == 1062):
logger.error(failure.type, failure.value, failure.getTraceback())
class PlateValuationPoster(Poster):
def __init__(self, item, dbinfo = ct.DB_INFO):
super(PlateValuationPoster, self).__init__(item)
self.dbname = PlateValuationCrawler.get_dbname()
self.table = PlateValuationCrawler.get_tablename()
self.connect = pymysql.connect(host=dbinfo['host'], port=dbinfo['port'], db=self.dbname, user=dbinfo['user'], passwd=dbinfo['password'], charset=ct.UTF8)
self.cursor = self.connect.cursor()
def store(self):
try:
insert_sql, params = self.item.get_insert_sql(self.table)
if insert_sql == None and params == None: return
self.cursor.execute(insert_sql, params)
self.connect.commit()
except Exception as e:
logger.error(e)
def on_error(self, failure):
if not (failure.type == IntegrityError and failure.value.args[0] == 1062):
logger.error(failure.type, failure.value, failure.getTraceback())
class InvestorSituationItemPoster(Poster):
def __init__(self, item, dbinfo = ct.DB_INFO):
super(InvestorSituationItemPoster, self).__init__(item)
self.dbname = InvestorCrawler.get_dbname()
self.table = InvestorCrawler.get_table_name()
self.dbpool = adbapi.ConnectionPool("pymysql", host = dbinfo['host'], db = self.dbname, user = dbinfo['user'], password = dbinfo['password'], charset = "utf8", cursorclass = pymysql.cursors.DictCursor, use_unicode = True)
def on_error(self, failure):
if not (failure.type == IntegrityError and failure.value.args[0] == 1062):
logger.error(failure.type, failure.value, failure.getTraceback())
def store(self):
query = self.dbpool.runInteraction(self.do_insert, self.item)
query.addErrback(self.on_error)
class MonthInvestorSituationItemPoster(Poster):
def __init__(self, item, dbinfo = ct.DB_INFO):
super(MonthInvestorSituationItemPoster, self).__init__(item)
self.dbname = MonthInvestorCrawler.get_dbname()
self.table = MonthInvestorCrawler.get_table_name()
self.dbpool = adbapi.ConnectionPool("pymysql", host = dbinfo['host'], db = self.dbname, user = dbinfo['user'], password = dbinfo['password'], charset = "utf8", cursorclass = pymysql.cursors.DictCursor, use_unicode = True)
def on_error(self, failure):
if not (failure.type == IntegrityError and failure.value.args[0] == 1062):
logger.error(failure.type, failure.value, failure.getTraceback())
def store(self):
query = self.dbpool.runInteraction(self.do_insert, self.item)
query.addErrback(self.on_error)
class StockLimitItemPoster(Poster):
def __init__(self, item, dbinfo = ct.DB_INFO, redis_host = None):
super(StockLimitItemPoster, self).__init__(item)
self.dbname = StockLimitCrawler.get_dbname()
self.table = StockLimitCrawler.get_tablename()
self.connect = pymysql.connect(host=dbinfo['host'], port=dbinfo['port'], db=self.dbname, user=dbinfo['user'], passwd=dbinfo['password'], charset=ct.UTF8)
self.cursor = self.connect.cursor()
def store(self):
try:
insert_sql, params = self.item.get_insert_sql(self.table)
if insert_sql == None and params == None: return
self.cursor.execute(insert_sql, params)
self.connect.commit()
except Exception as e:
logger.debug(e)
def on_error(self, failure):
if not (failure.type == IntegrityError and failure.value.args[0] == 1062):
logger.error(failure.type, failure.value, failure.getTraceback())