Esempio n. 1
0
    async def __call__(self, scope, receive, send):
        # locals inside the app function (send_wrapper) can't be assigned to,
        # as the interpreter detects the assignment and thus creates a new
        # local variable within that function, with that name.
        instance = {'http_status_code': None}

        def send_wrapper(response):
            if response['type'] == 'http.response.start':
                instance['http_status_code'] = response['status']
            return send(response)

        if scope['type'] != 'http':
            alog.info(
                f"ASGI scope of type {scope['type']} is not supported yet")
            await self.app(scope, receive, send)
            return

        try:
            metric_name = self.metric_namer(scope)
        except AttributeError as e:
            alog.error(
                f"Unable to extract metric name from asgi scope: {scope}, skipping statsd timing"
            )
            alog.error(f" -> exception: {e}")
            await self.app(scope, receive, send)
            return

        def emit(stats):
            statsd_tags = [
                f"http_status:{instance['http_status_code']}",
                f"http_method:{scope['method']}"
            ]
            self.client.timing(f"{metric_name}",
                               stats.time,
                               tags=statsd_tags + ["time:wall"])
            self.client.timing(f"{metric_name}",
                               stats.cpu_time,
                               tags=statsd_tags + ["time:cpu"])

        with TimingStats(metric_name) as stats:
            try:
                await self.app(scope, receive, send_wrapper)
            except Exception:
                stats.stop()
                instance['http_status_code'] = 500
                emit(stats)
                raise
        emit(stats)
    def send_mail(self, content, send_from, send_to, password):
        msg = MIMEText(content)
        msg['Subject'] = "HackMD notify!"
        msg['From'] = send_from
        msg['To'] = send_to

        try:
            server = smtplib.SMTP(self.smtp_server, self.port)
            server.ehlo()
            server.starttls()
            server.ehlo()
            server.login(send_from, password)
            server.sendmail(send_from, send_to, msg.as_string())
            server.quit()
        except:
            alog.error("send mail failed")
Esempio n. 3
0
    def on_message(self, message):
        """Handler for parsing WS messages."""
        response = json.loads(message)
        
        # if response
        if "id" in response:
            if "result" in response:
                result = response["result"]
            elif "error" in response:
                alog.error(response["error"])
                return
            else:
                return
            
            id = response["id"]
            if id == self._id:
                if self._method == "public/auth":
                    self._authInfo["access_token"] = result["access_token"]
                    self._authInfo["expires_in"] = result["expires_in"]
                    self._authInfo["refresh_token"] = result["refresh_token"]
                    self._authInfo["scope"] = result["scope"]
                    self._authInfo["token_type"] = result["token_type"]
                    
                    alog.info("access_token: {}".format(self._authInfo["access_token"]))
                    
                    self.emit('subscribe')

                    # wst = threading.Thread(target=self.__on_expires_in)
                    # wst.daemon = True
                    # wst.start()
                    return
                elif self._method == "public/subscribe" or self._method == "private/subscribe":
                    self.emit('subscribed', result)
                    return

                
        alog.info(message)
        if "method" in response:
            method = response["method"]
            if method == "subscription":
                params = response["params"]
                channel = params["channel"]
                #if "user.orders" in channel:
                self.emit('orders', channel, params["data"])
Esempio n. 4
0
def addTemplate(eventName, eventDate, eventLink, eventAdress, eventCity,
                idEvent):
    if eventAdress is None:
        return
    urlOfAddress = "http://wispi.tk"
    try:
        urlOfAddress = "https://www.google.fr/maps/place/" + urllib.parse.quote(
            eventAdress)
    except Exception as e:
        alog.error("Cant parse adress " + eventAdress + str(e))

    return Template.GenericElement(
        eventName,
        subtitle=arrow.get(eventDate).humanize(),
        item_url=eventLink,
        image_url=searchImage.getImageUrl(eventName),
        buttons=[
            Template.ButtonWeb("Open in Map", urlOfAddress),
            Template.ButtonWeb("Open Event", eventLink),
            Template.ButtonShare()
        ])
Esempio n. 5
0
async def consume(queue):
    """
    Post rs232 data into server
    :param queue
    """
    async with aiohttp.ClientSession() as session:
        try:
            while True:
                # wait for an data from producer
                data = await queue.get()
                # process the item
                alog.info(f"consuming id:{id(data)}")
                status, result = await async_post(session, url_boards, data)
                if status != 201:
                    alog.error(f"error: id:{id(data)}, {status}, {result}")
                    await queue.put(data)
                # simulate i/o operation using sleep
                await asyncio.sleep(random.random())
                # Notify the queue that the item has been processed
                queue.task_done()
        except Exception as e:
            alog.info(f"Finish: {e}.")
Esempio n. 6
0
    def on_message(self, message):
        '''Handler for parsing WS messages.'''
        # Check if ping message
        ping_message = message[:14]
        alog.debug(ping_message)
        if ping_message == PING_MESSAGE_PREFIX:
            alog.debug(message)
            return self.emit('ping', message)

        message = json.loads(message)
        alog.debug(json.dumps(message, indent=4, sort_keys=True))

        action = message['action'] if 'action' in message else None

        try:
            if action:
                table = message['table']
                event_name = ''
                if table in constants.CHANNELS:
                    event_name = "%s:%s" % (action, table)
                else:
                    if len(message['data']) > 0:
                        instrument = message['data'][0]['symbol']
                        event_name = self.gen_action_event_key(action,
                                                               instrument,
                                                               table)
                alog.debug(event_name)
                self.emit(event_name, message)
            elif 'subscribe' in message:
                self.emit('subscribe', message)
            elif 'error' in message:
                self.error(message['error'])
            elif 'status' in message:
                self.emit('status', message)

        except:
            alog.error(traceback.format_exc())
Esempio n. 7
0
 def test_error(self):
     alog.error(msg)
Esempio n. 8
0
 def on_error(self, error):
     alog.error(error)
     raise DeribitWebsocketConnectionError(error)
Esempio n. 9
0
 def on_error(self, e, data=None):
     self.stop = True
     self.error = e
     alog.error('{} - data: {}'.format(e, data))
     self.close()
Esempio n. 10
0
 def error(self, err):
     alog.debug('this error...')
     self._error = err
     alog.error(err)
     self.exit()