async def send_message( targets: List[str], text: str, config: Dict[str, Any], loop: Optional[asyncio.AbstractEventLoop] = None, ) -> None: if loop is None: loop = asyncio.get_running_loop() server_log.debug(f"Sending email to {targets}") config = config["email-confirmation"]["smtp"] for i in ("host", "login", "password"): if config.get(i) is None: server_log.info( f"Bad configuration, unable to send the following email:\n{text}" ) return await loop.run_in_executor( None, _send_message, targets, text, config["host"], config["login"], config["password"], )
def _check_ret_callback(self, is_valid): reply_dict = dict() reply_dict['code'] = 0 reply_dict['record'] = dict() if is_valid: reply_dict['code'] = 1 user_uid = self.get_argument('user_id') + '_' + self.get_argument( 'user_pf') reply_dict['record'] = self.application.record_mod.get_record( user_uid) reply = str(self.get_argument('callback')) + '(' + json.dumps( reply_dict) + ')' self.write( reply ) # this function will add '//' to words, overwrite reply !!! server_log.info('read: ' + reply) else: '''wrong user_id or user_key''' reply_dict['code'] = 1 reply = str(self.get_argument( 'callback')) + '(' + "{'code':0, 'msg':'invid userid'}" + ')' self.write(reply) self.finish()
def check_info(self, user_id, user_key, zoneid, callback): self.check_ret_callback = callback if cfg.IS_REMOTE == 0: self.check_ret_callback(True) else: is_need_check = False if user_id in LoginChecker.user_cache.keys(): if user_key in LoginChecker.user_cache[user_id]: server_log.warn('check ok, account in cache') self.check_ret_callback(True) else: is_need_check = True else: '''insure key-set in user_cache''' LoginChecker.user_cache[user_id] = set() server_log.warn('user_cache len: %d, user add: %s' % (len(LoginChecker.user_cache), user_id)) is_need_check = True if is_need_check: server_log.info('need check_info, user_id = ' + user_id + 'user_key = ' + user_key) '''should check from tencent server''' request = tornado.httpclient.HTTPRequest( cfg.TENCENT_ACCOUNT_SERVER + '/?openid=' + user_id + '&openkey=' + user_key + '&user_pf=' + zoneid + '&api=k_playzone_userinfo' + '&platform=qzone' + '&callback=cb', method='GET') server_log.info('new active url: ' + request.url) self.chk_client.fetch(request, callback=self._check_response_callback)
def _check_response_callback(self, response): server_log.info('check_callback: ' + str(response.body)) is_valid = False if response and response.body: j_body = json.JSONDecoder().decode(response.body.lstrip('cb(').rstrip(')')) server_log.warn('in _check_response_callback0, user_cache len: %d' % len(LoginChecker.user_cache)) # [[ if 'data'in j_body and j_body['is_ok'] == 1 and 'openid' in j_body and 'openkey' in j_body: openid = j_body['openid'] if openid in LoginChecker.user_cache: pass else: LoginChecker.user_cache[openid] = set() server_log.warn('in _check_response_callback1, user_cache len: %d' % len(LoginChecker.user_cache)) LoginChecker.user_cache[openid].add(j_body['openkey']) is_valid = True # ==============> test # openid = j_body['openid'] # if openid in LoginChecker.user_cache: # pass # else: # LoginChecker.user_cache[openid] = set() # LoginChecker.user_cache[openid].add(j_body['openkey']) # is_valid = True # ]] self.check_ret_callback(is_valid)
def push_record_to_db_callback(self, response): if response.body: pass else: # TODO : error handle pass server_log.info('syn immediately response: ' + str(response.body))
def check_info(self, user_id, user_key, zoneid, callback): self.check_ret_callback = callback if cfg.IS_REMOTE == 0: self.check_ret_callback(True) else: is_need_check = False if user_id in LoginChecker.user_cache.keys(): if user_key in LoginChecker.user_cache[user_id]: server_log.warn('check ok, account in cache') self.check_ret_callback(True) else: is_need_check = True else: '''insure key-set in user_cache''' LoginChecker.user_cache[user_id] = set() server_log.warn('user_cache len: %d, user add: %s' % (len(LoginChecker.user_cache), user_id)) is_need_check = True if is_need_check: server_log.info('need check_info, user_id = ' + user_id + 'user_key = ' + user_key) '''should check from tencent server''' request = tornado.httpclient.HTTPRequest(cfg.TENCENT_ACCOUNT_SERVER + '/?openid=' + user_id + '&openkey=' + user_key + '&user_pf=' + zoneid + '&api=k_playzone_userinfo' + '&platform=qzone' + '&callback=cb', method='GET') server_log.info('new active url: ' + request.url) self.chk_client.fetch(request, callback=self._check_response_callback)
def post(self, *args, **kwargs): bill_str = self.request.body bill_dict = json.JSONDecoder().decode(bill_str) self.application.db.bill.insert_one(bill_dict) server_log.info('db write bill: ' + str(bill_dict)) self.write("{'ok': 1, 'msg': 'push bill'}")
def push_records_to_db_callback(self, response): if response.body: self.batch_on_pushing.clear() # server_log.info('syn response: ' + str(response.body)) else: # TODO : error handle: 备份没有提交的 on_push 到现有的 batch 上 self.batch_on_pushing.update(self.batch) self.batch = copy.deepcopy(self.batch_on_pushing) self.batch_on_pushing.clear() server_log.info('push error !!!!!!!!!!!!! syn response: ' + str(response.body))
def __init__(self): handlers = [(r"/writeDirtyRecord", WriteDirtyRecordHandler), (r"/readRecord", ReadRecordHandler), (r"/cmd", CommandHandler)] self.record_mod = record.Record(options.db_addr, options.db_port) self.running = True server_log.info('record server start on db[' + options.db_addr + ':' + str(options.db_port) + ']') tornado.web.Application.__init__(self, handlers, debug=False)
async def create_redis_pool(app: web.Application) -> None: server_log.info("Creating redis connection") config = copy(app["config"]["redis"]) host = config.pop("host") port = config.pop("port") pool = await aioredis.create_pool((host, port), **config) app["rd_conn"] = pool
def __init__(self): handlers = [ (r"/writeDirtyRecord", WriteDirtyRecordHandler), (r"/readRecord", ReadRecordHandler), (r"/cmd", CommandHandler) ] self.record_mod = record.Record(options.db_addr, options.db_port) self.running = True server_log.info('record server start on db[' + options.db_addr + ':' + str(options.db_port) + ']') tornado.web.Application.__init__(self, handlers, debug=False)
def __init__(self): handlers = [(r"/ranklist", GetRankListHandler), (r"/billinfo", WriteBillToDBHandler)] server_log.info('db server start on db[' + options.db_addr + ':' + str(options.db_port) + ']') conn = pymongo.MongoClient(options.db_addr, options.db_port) self.db = conn['dota'] self.db.jjc.create_index('honour') self._predeploy_users() tornado.web.Application.__init__(self, handlers, debug=True)
def get_record_old(self, user_uid): # find it from record batch first server_log.info('get record. user_uid=' + user_uid) if not self.is_pushing and user_uid in self.batch: # return json.JSONDecoder().decode(self.batch[user_uid]) # json to dict server_log.info('batch : ' + str(self.batch)) return self.batch[user_uid] # json to dict elif self.is_pushing and user_uid in self.batch_on_pushing: # return json.JSONDecoder().decode(self.batch_on_pushing[user_uid]) server_log.info('batch_on_pushing : ' + str(self.batch_on_pushing)) return self.batch_on_pushing[user_uid] else: find_ret = self.db.user.find_one({'user_uid': user_uid}) if find_ret: del find_ret['_id'] reply_dict = dict() if 'record' in find_ret and type(find_ret['record']) is dict: # reply_dict = dict((key.encode('ascii'), value) for key, value in find_ret['record'].items()) reply_dict = find_ret['record'] return reply_dict else: server_log.info('not find record of user_uid=' + user_uid + ', make default record !!!') record_doc = dict() record_doc['user_uid'] = user_uid record_doc['record'] = Record.default_record() self.db.user.insert(record_doc) reply_dict = Record.default_record() return reply_dict
def __init__(self): handlers = [(r"/", WriteRecordToDBHandler), (r"/billinfo", WriteBillToDBHandler)] server_log.info('db server start on db[' + options.db_addr + ':' + str(options.db_port) + ']') conn = pymongo.MongoClient(options.db_addr, options.db_port) self.db = conn['dota'] self.db.user.create_index('user_uid') self.db.bill.create_index('billno') tornado.web.Application.__init__(self, handlers, debug=True)
def __init__(self): handlers = [ (r"/ranklist", GetRankListHandler), (r"/billinfo", WriteBillToDBHandler) ] server_log.info('db server start on db[' + options.db_addr + ':' + str(options.db_port) + ']') conn = pymongo.MongoClient(options.db_addr, options.db_port) self.db = conn['dota'] self.db.jjc.create_index('honour') self._predeploy_users() tornado.web.Application.__init__(self, handlers, debug=True)
def post(self, *args, **kwargs): command_str = self.request.body command_dict = json.JSONDecoder().decode(command_str) try: if command_dict["type"] == 0: self.application.running = False self.write("{'ok': 1, 'msg': 'recordserver stop servering'}") server_log.info('recordserver stop servering') elif command_dict["type"] == 1: self.application.running = True self.write("{'ok': 1, 'msg': 'recordserver start servering'}") server_log.info('recordserver start servering') except KeyError: self.write("{'ok': 0, 'msg': 'exception occur'}")
def emit(self, event: Event) -> None: """Emits event handling it's scope.""" if isinstance(event, LocalEvent): task = self.notify_channel(event) elif isinstance(event, OuterEvent): task = self.notify_channels(event) elif isinstance(event, GlobalEvent): task = self.notify_everyone(event) else: server_log.info(f"Emitter: unknown event type: {event}") return # TODO: use self.app.loop.ensure_future() ? asyncio.create_task(task)
def post(self, *args, **kwargs): batch_str = self.request.body # print 'will write this: ', str(batch_str) batch_dict = json.JSONDecoder().decode(batch_str) # modify_time = time.ctime() modify_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) for user_id, record_dict in batch_dict.items(): """ split the dict, and update data partly use '$set' to db""" set_dict = dict() set_dict['user_uid'] = user_id set_string = '' for k, v in record_dict.items(): set_string += "'record.%s':'%s'," % (k, v) set_dict['record.%s' % k] = v set_dict['modify_time'] = modify_time self.application.db.user.update({'user_uid': user_id}, {'$set': set_dict}, True, False) server_log.info('db write this: user_uid:' + user_id + ' doc: ' + str(set_dict)) self.write("{'ok': 1, 'msg': 'push record'}")
def __init__(self): handlers = [(r'/', IndexHandler), (r'/login', LoginHandler), (r'/userDetail', UserDetailHandler), (r'/userDetail/changeGold', UserDetailChangeGoldHandler), (r'/userDetail/changeZuan', UserDetailChangeZaunHandler), (r'/test', TestHandler)] server_log.info('gm server start on db[' + options.db_addr + ':' + str(options.db_port) + ']') conn = pymongo.MongoClient(options.db_addr, options.db_port) self.db = conn['dota'] tornado.web.Application.__init__( self, handlers, template_path=os.path.join(os.path.dirname(__file__), "templates"), static_path=os.path.join(os.path.dirname(__file__), "static"), ui_modules={'UserData': UserDataModule}, debug=True)
def _check_ret_callback(self, is_valid): reply_dict = dict() reply_dict['code'] = 0 reply_dict['record'] = dict() if is_valid: reply_dict['code'] = 1 user_uid = self.get_argument('user_id') + '_' + self.get_argument('user_pf') reply_dict['record'] = self.application.record_mod.get_record(user_uid) reply = str(self.get_argument('callback')) + '(' + json.dumps(reply_dict) + ')' self.write(reply) # this function will add '//' to words, overwrite reply !!! server_log.info('read: ' + reply) else: '''wrong user_id or user_key''' reply_dict['code'] = 1 reply = str(self.get_argument('callback')) + '(' + "{'code':0, 'msg':'invid userid'}" + ')' self.write(reply) self.finish()
def __init__(self): handlers = [ (r"/writeStat", WriteStatToDBHandler), (r"/querySrvState", QuerySrvStateHandler), (r"/cmd", CommandHandler), ] server_log.info('stat server start on port: ' + str(options.port) + ' db[' + options.db_addr + ':' + str(options.db_port) + ']') conn = pymongo.MongoClient(options.db_addr, options.db_port) self.db = conn['dota'] self.db.stat.create_index('user_uid') server_log.info('connect server OK') self.client = tornado.httpclient.AsyncHTTPClient() """server state""" self.server_running = True self.server_state_msg = "" tornado.web.Application.__init__(self, handlers, debug=True)
def get(self): """as it is not a strictly important part, need not to check user certification""" user_uid = self.get_argument('openid') + '_' + self.get_argument('user_pf') modify_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) push_str = self.get_argument('stat') push_dict = json.JSONDecoder().decode(push_str) push_dict['modify_time'] = modify_time self.application.db.stat.update({'user_uid': user_uid}, { '$push': { 'actions': { '$each': [push_dict], '$slice': -WriteStatToDBHandler._MAX_ACTION_EACH_ID }, }, '$set': { 'last_modify': modify_time }}, True, False) server_log.info(str(push_dict)) self.write(str(self.get_argument('callback') + '(' + "{'ok': 1}" + ')'))
def __init__(self): handlers = [ (r"/", IndexHandler), (r"/login", LoginHandler), (r"/userDetail", UserDetailHandler), (r"/userDetail/changeGold", UserDetailChangeGoldHandler), (r"/userDetail/changeZuan", UserDetailChangeZaunHandler), (r"/test", TestHandler), ] server_log.info("gm server start on db[" + options.db_addr + ":" + str(options.db_port) + "]") conn = pymongo.MongoClient(options.db_addr, options.db_port) self.db = conn["dota"] tornado.web.Application.__init__( self, handlers, template_path=os.path.join(os.path.dirname(__file__), "templates"), static_path=os.path.join(os.path.dirname(__file__), "static"), ui_modules={"UserData": UserDataModule}, debug=True, )
def _check_response_callback(self, response): server_log.info('check_callback: ' + str(response.body)) is_valid = False if response and response.body: j_body = json.JSONDecoder().decode( response.body.lstrip('cb(').rstrip(')')) server_log.warn( 'in _check_response_callback0, user_cache len: %d' % len(LoginChecker.user_cache)) # [[ if 'data' in j_body and j_body[ 'is_ok'] == 1 and 'openid' in j_body and 'openkey' in j_body: openid = j_body['openid'] if openid in LoginChecker.user_cache: pass else: LoginChecker.user_cache[openid] = set() server_log.warn( 'in _check_response_callback1, user_cache len: %d' % len(LoginChecker.user_cache)) LoginChecker.user_cache[openid].add(j_body['openkey']) is_valid = True # ==============> test # openid = j_body['openid'] # if openid in LoginChecker.user_cache: # pass # else: # LoginChecker.user_cache[openid] = set() # LoginChecker.user_cache[openid].add(j_body['openkey']) # is_valid = True # ]] self.check_ret_callback(is_valid)
def get(self): """as it is not a strictly important part, need not to check user certification""" user_uid = self.get_argument('openid') + '_' + self.get_argument( 'user_pf') modify_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) push_str = self.get_argument('stat') push_dict = json.JSONDecoder().decode(push_str) push_dict['modify_time'] = modify_time self.application.db.stat.update({'user_uid': user_uid}, { '$push': { 'actions': { '$each': [push_dict], '$slice': -WriteStatToDBHandler._MAX_ACTION_EACH_ID }, }, '$set': { 'last_modify': modify_time } }, True, False) server_log.info(str(push_dict)) self.write( str(self.get_argument('callback') + '(' + "{'ok': 1}" + ')'))
def get_record(self, user_uid): # server_log.info('get record. user_uid=' + user_uid) # if user_uid not in self.cache: # server_log.info('not in cache') find_ret = self.db.user.find_one({'user_uid': user_uid}) if find_ret: server_log.info('db find') del find_ret['_id'] reply_dict = dict() if 'record' in find_ret and type(find_ret['record']) is dict: # reply_dict = dict((key.encode('ascii'), value) for key, value in find_ret['record'].items()) reply_dict = find_ret['record'] """attach unpushed record item to Record(old) from db""" if user_uid in self.batch_on_pushing: server_log.warning('attach record_on_pushing: ' + user_uid + ', record: ' + str(self.batch_on_pushing[user_uid])) reply_dict.update(self.batch_on_pushing[user_uid]) if user_uid in self.batch: server_log.info('attach record_batch: ' + user_uid + ', record: ' + str(self.batch[user_uid])) reply_dict.update(self.batch[user_uid]) """add unique number id""" if 'userno' not in reply_dict: reply_dict['userno'] = self._make_userno() else: server_log.info('not find record of user_uid=' + user_uid + ', make default record !!!') record_doc = dict() record_doc['user_uid'] = user_uid record_doc['record'] = Record.default_record() record_doc['record']['userno'] = self._make_userno() self.db.user.insert(record_doc) reply_dict = record_doc['record'] return reply_dict
async def create_postgres_connection(app: aiohttp.web.Application) -> None: server_log.info("Creating postgres connection") connection = await asyncpg.create_pool(**app["config"]["postgres"]) app["pg_conn"] = connection
def main(): client_log.debug('client debug demo') server_log.info('server log demo')
async def close_redis_pool(app: web.Application) -> None: server_log.info("Closing redis connection") app["rd_conn"].close() await app["rd_conn"].wait_closed()
def main(): client_log.debug("client debug demo") server_log.info("server log demo")
def get(self): if not self.application.running: self.send_error() return print 'api uri:', self.request.uri server_log.info('api uri:' + self.request.uri) try: openid = self.get_argument('openid') openkey = self.get_argument('openkey') platform = self.get_argument('platform') user_pf = self.get_argument('user_pf') api = self.get_argument('api') callback = self.get_argument('callback') except KeyError: server_log.warning("except KeyError: Failed to get argument", exc_info=True) server_log.info('handle api:' + api) if api == 'k_userinfo': jdata = self.application.api.call('/v3/user/get_info', { 'openid': openid, 'openkey': openkey, 'pf': platform, }) jdata['is_ok'] = 1 jdata['openid'] = openid jdata['openkey'] = openkey # reply = json.JSONEncoder().encode(jdata) reply = json.dumps(jdata, ensure_ascii=False).encode('utf8') elif api == 'k_islogin': jdata = self.application.api.call('/v3/user/is_login', { 'openid': openid, 'openkey': openkey, 'pf': platform, }) jdata['is_ok'] = 1 reply = json.dumps(jdata, ensure_ascii=False).encode('utf8') elif api == 'k_playzone_userinfo': jdata = self.application.api.call( '/v3/user/get_playzone_userinfo', { 'openid': openid, 'openkey': openkey, 'pf': platform, 'zoneid': int(user_pf) }) jdata['is_ok'] = 1 jdata['openid'] = openid jdata['openkey'] = openkey reply = json.dumps(jdata, ensure_ascii=False).encode('utf8') elif api == 'k_buy_playzone_item': itemid = self.get_argument('itemid') count = self.get_argument('count') jdata = self.application.api.call( '/v3/user/buy_playzone_item', { 'openid': openid, 'openkey': openkey, 'pf': platform, 'zoneid': int(user_pf), 'itemid': itemid, 'count': int(count) }) jdata['is_ok'] = 1 reply = json.dumps(jdata, ensure_ascii=False).encode('utf8') self.application.push_billinfo_to_db(openid, user_pf, itemid, jdata) else: reply = "{'is_ok':0, 'msg': 'invalid api'}" print('reply: ' + reply) # lkj bug: how to show unicode - chinese reply = callback.encode('utf8') + '(' + reply + ')' self.write(reply)
class CommandHandler(tornado.web.RequestHandler): # def data_received(self, chunk): # pass def post(self, *args, **kwargs): command_str = self.request.body command_dict = json.JSONDecoder().decode(command_str) try: if command_dict["type"] == 0: self.application.running = False self.write("{'ok': 1, 'msg': 'openapi server stop servering'}") server_log.info('openapi server stop servering') print 'openapi server stop servering' elif command_dict["type"] == 1: self.application.running = True self.write( "{'ok': 1, 'msg': 'openapi server start servering'}") server_log.info('openapi server start servering') print 'openapi server start servering' except KeyError: self.write("{'ok': 0, 'msg': 'exception occur'}") if __name__ == "__main__": server_log.info('openapiserver start.') app = Application() http_server = tornado.httpserver.HTTPServer(app) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start()
class CommandHandler(tornado.web.RequestHandler): # def data_received(self, chunk): # pass def post(self, *args, **kwargs): command_str = self.request.body command_dict = json.JSONDecoder().decode(command_str) try: if command_dict["type"] == 0: self.application.running = False self.write("{'ok': 1, 'msg': 'openapi server stop servering'}") server_log.info('openapi server stop servering') print 'openapi server stop servering' elif command_dict["type"] == 1: self.application.running = True self.write("{'ok': 1, 'msg': 'openapi server start servering'}") server_log.info('openapi server start servering') print 'openapi server start servering' except KeyError: self.write("{'ok': 0, 'msg': 'exception occur'}") if __name__ == "__main__": server_log.info('openapiserver start.') app = Application() http_server = tornado.httpserver.HTTPServer(app) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start()
def get(self): if not self.application.running: self.send_error() return print 'api uri:', self.request.uri server_log.info('api uri:' + self.request.uri) try: openid = self.get_argument('openid') openkey = self.get_argument('openkey') platform = self.get_argument('platform') user_pf = self.get_argument('user_pf') api = self.get_argument('api') callback = self.get_argument('callback') except KeyError: server_log.warning("except KeyError: Failed to get argument", exc_info=True) server_log.info('handle api:' + api) if api == 'k_userinfo': jdata = self.application.api.call('/v3/user/get_info', { 'openid': openid, 'openkey': openkey, 'pf': platform, }) jdata['is_ok'] = 1 jdata['openid'] = openid jdata['openkey'] = openkey # reply = json.JSONEncoder().encode(jdata) reply = json.dumps(jdata, ensure_ascii=False).encode('utf8') elif api == 'k_islogin': jdata = self.application.api.call('/v3/user/is_login', { 'openid': openid, 'openkey': openkey, 'pf': platform, }) jdata['is_ok'] = 1 reply = json.dumps(jdata, ensure_ascii=False).encode('utf8') elif api == 'k_playzone_userinfo': jdata = self.application.api.call('/v3/user/get_playzone_userinfo', { 'openid': openid, 'openkey': openkey, 'pf': platform, 'zoneid': int(user_pf) }) jdata['is_ok'] = 1 jdata['openid'] = openid jdata['openkey'] = openkey reply = json.dumps(jdata, ensure_ascii=False).encode('utf8') elif api == 'k_buy_playzone_item': itemid = self.get_argument('itemid') count = self.get_argument('count') jdata = self.application.api.call('/v3/user/buy_playzone_item', { 'openid': openid, 'openkey': openkey, 'pf': platform, 'zoneid': int(user_pf), 'itemid': itemid, 'count': int(count) }) jdata['is_ok'] = 1 reply = json.dumps(jdata, ensure_ascii=False).encode('utf8') self.application.push_billinfo_to_db(openid, user_pf, itemid, jdata) else: reply = "{'is_ok':0, 'msg': 'invalid api'}" print('reply: ' + reply) # lkj bug: how to show unicode - chinese reply = callback.encode('utf8') + '(' + reply + ')' self.write(reply)
OAuth2App.add_routes(oauth2_routes) OAuth2App["auth_sessions"] = {} APIApp.add_subapp("/v0/", APIv0App) APIApp.add_subapp("/oauth2/", OAuth2App) app.add_subapp("/api/", APIApp) # logging setup setup_logging(app) # SSL setup ssl_context: Optional[ssl.SSLContext] = None if app["args"].force_ssl: server_log.info("SSL: Using certificate") ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) ssl_section = app["config"]["ssl"] ssl_context.load_cert_chain(ssl_section["cert-chain-path"], ssl_section["cert-privkey-path"]) server_log.info( f'Running in {"debug" if app["args"].debug else "production"} mode') # debug setup if app["args"].debug: from routes.debug import routes as debug_routes from routes.debug import shutdown as debug_shutdown Debugapp = web.Application()
async def close_postgres_connection(app: aiohttp.web.Application) -> None: server_log.info("Closing postgres connection") await app["pg_conn"].close()