async def connect(self): ''' 连接 RabbitMQ,并初始化exchanges :param reconnect: 若连接非初连接,进行重置操作 :return: ''' # 若已连接,则不进行连接操作 if self._connected: return logger_info.info('Host:%s,Port:%s - Try connecting RabbitMQ!' % (self._host, self._port)) try: transport, protocol = await aioamqp.connect( host=self._host, port=self._port, login=self._username, password=self._pwd, virtualhost=self._vhost) except aioamqp.AmqpClosedConnection as e: logger_error.error('Rabbit connection error:%s' % e) return finally: if self._connected: return self._protocol = protocol self._channel = await protocol.channel() self._connected = True await self._init_exchanges() logger_info.info("%s - RabbitMQ initialize success!" % self)
def _send_error_email(self, exception): try: subject = "[%s]Internal Server Error" % options.SITE_NAME body = exception if options.SEND_MAIL: send_mail(options.MAIL_LIST, subject, body) # todo mail sender should be async except: logger_error.error(traceback.format_exc())
def __init__(self, uri=None, db=None): try: if not uri: uri = options['MONGO_URI'] self.client = motor.motor_tornado.MotorClient(uri) if not db: db = options['MONGO_DB'] self.db = self.client[db] except AttributeError as e: logger_error.error('AttributeError - %s' % e)
async def _check_connection(self, task_id, *args, **kwargs): if self._connected and self._channel and self._channel.is_open: logger_info.info("%s - RabbitMQ connection ok." % self) return logger_error.error("%s - CONNECTION LOSE! START RECONNECT RIGHT NOW!" % self) self._connected = False self._protocol = None self._channel = None self._event_handler = {} asyncio.get_event_loop().create_task(self.connect())
async def _init_exchanges(self): exchanges = options.EXCHANGES_DICT try: for e_type, e_names in exchanges.items(): if e_type not in ['fanout', 'topic', 'direct']: raise Exception( "GET THE WRONG EXCHANGE TYPE! PLEASE CHECK OUT!") for e_name in e_names: await self.producer(e_name, e_type) except Exception as e: logger_error.error('%s - Exchange init error : %s' % (self, e))
def send_mail(to_list, sub, content): me = "<" + mail_user + "@" + mail_postfix + ">" msg = MIMEText(content, _subtype='plain', _charset='utf-8') msg['Subject'] = sub msg['From'] = me msg['To'] = ";".join(to_list) # 将收件人列表以‘;’分隔 try: server = smtplib.SMTP() # 连接服务器 server.connect(mail_host) # 登录操作 server.login(mail_user, mail_pass) server.sendmail(me, to_list, msg.as_string()) logger_debug.debug('send mail success') server.close() return True except Exception as e: logger_error.error('send mail error: %s' % e) return False
async def publish(self, msg, exchange_name='', routing_key='', *args, **kwargs): ''' 广播至指定的exchange :param msg: 接受dict,处理成json格式 :return: ''' if not self._connected: logger_error.error("RabbitMQ not ready right now!", caller=self) return json_msg = json.dumps(msg) await self._channel.basic_publish(payload=json_msg, exchange_name=exchange_name, routing_key=routing_key, *args, **kwargs) logger_info.info('%s - Publish messages success! name:%s' % (self, exchange_name))
def write_error(self, status_code, **kwargs): msg = '' # override debug = options.DEBUG self.set_status(status_code) # always return 200 OK for API errors try: exc_info = kwargs.pop('exc_info') e = exc_info[1] logger_error.error('status_code %d' % status_code) if isinstance(e, HTTPAPIError): msg = str(e) elif isinstance(e, HTTPError): self.set_status(status_code) else: # for unknown error e = HTTPAPIError(10001) msg = str(e) exception = "".join( [ln for ln in traceback.format_exception(*exc_info)]) logger_error.error(exception) if status_code == 500 and not debug: self._send_error_email(exception) if debug: if status_code == 200: e.response["exception"] = exception msg = str(e) # self.clear() self.set_header("Content-Type", "application/json; charset=UTF-8") self.finish(msg) except: logger_error.error(traceback.format_exc()) return super(APIHandler, self).write_error(status_code, **kwargs)